Why functoin in useEffect does not accept parameters?

45 views Asked by At

I have been studying about the useEffect hook in reactjs. and i studied the we can not pass parameters to useEffect function, this is understandable. but tried to search for the reason the why is it not allowed to pass parameters in useEffect function.

useEffect((parameter)=> {
      console.log(parameter)
    })

does anyone know?

I searched alot for it, but i could not find any reasonable answer for it.

3

There are 3 answers

0
Elias Salom On BEST ANSWER

The function passed to useEffect in React is not designed to receive parameters directly because it is called by React and not by your code directly. To use parameters inside the effect function, you can use variables from the scope of the component or define the effect function inside the component where it can access the component's state and props.


import React, { useEffect, useState } from 'react';

function MyComponent() {
  const [parameter, setParameter] = useState('initialValue');

  useEffect(() => {
    console.log(parameter);
    // You can use parameter here
  }, [parameter]); // Depend on parameter

  // Some code to change parameter
  const handleChangeParameter = () => {
    setParameter('newValue');
  };

  return (
    <div>
      <button onClick={handleChangeParameter}>Change Parameter</button>
    </div>
  );
}

export default MyComponent;

0
T.J. Crowder On

Your code doesn't call useEffect's callback, React's code does. So only React's code could pass arguments to it. They could have designed it to have arguments, but they didn't, probably at least in part because it's not clear what arguments React's code would pass to it.

The code in the effect callback has access to all of the constants and variables accessible in the component body, which makes those effectively (not literally) parameters to the callback. That's entirely sufficient for what the callback is for: Interfacing/synchronizing with an external system (docs).

0
Mycolaos On

Because instead of passing additional parameters it uses the concept of closure. This means, that your function can access the variables outside of its body.

If you need to use external parameters inside useEffect you have to declare them in dependency array. This way, the useEffect hook can rerun your function when the parameter changes.

For example:

const MyComponent = (props) => {
  const { parameter } = props;
  
  useEffect(() => {
    console.log(parameter);
  }, [parameter]);
}