7

So I have this React component which uses the useEffect() hook:

const [stateItem, setStateItem] = useState(0);

useEffect(() => {
  if (condition) {
    myFunction();
  }
}, [stateItem]);

const myFunction = () => {
  return 'hello';
}

React gives me a warning about 'myFunction' being a missing dependency. I (think I) understand why and I've read through many similar questions asking for more or less the same thing, but the answer is always 'move your function into the useEffect hook'. This would be fine if not for myFunction being called from different places, e.g.:

...
return (
  <Button onClick={() => myFunction()} />
);

therefore I cannot put my function inside the useEffect hook.

One answer to a similar question was to put the function outside the component, but that would require me to pass a lot of data to my functions, e.g. const myFunction(stateItem, setStateItem, someProp) => { stuff };

which gets extremely tedious when there are several functions with many props, state hooks etc. to pass.

Aside from putting a linter ignore comment above the useEffect hook, is there anything more practical to do about this? I'm finding these things to make using react hooks very impractical.

4
  • 1
    Can you post the whole component ?
    – CptKicks
    Commented Nov 29, 2019 at 10:34
  • Move you function above useEffect as it's declared as const.
    – ZiiMakc
    Commented Nov 29, 2019 at 11:01
  • @CptChix Those two pieces of code are together a full but simple example of a component that would have this issue.
    – paddotk
    Commented Nov 29, 2019 at 11:59
  • @ RTW It works fine like this, not sure if that's a newer React support thing.
    – paddotk
    Commented Nov 29, 2019 at 11:59

4 Answers 4

7

I've had issues with this.

React is always trying to keep your effects up-to-date. If you don't pass a dependency array, React will run that effect after every render, just in case.

This will run on every render

useEffect(()=> {
  // DO SOMETHING
});

If you pass an empty array, you're basically telling that your effect does not depend on anything, and it's safe to run it only once.

This will only run once

useEffect(()=> {
  // DO SOMETHING
},[]);

If you populate the dependency array, you're telling the your effect depend on those specific things, and if any of them changes, the effect needs to be run again, otherwise, it doesn't have to.

This will only run if someProp or someFunction changes.

useEffect(()=> {
  // DO SOMETHING
},[someProp,someFuction]);

NOTE: Remember functions, objects and arrays are compared by reference

So, basically your options are:

  • Move the function to the effect's body.
  • Add it do the dependency array

If you choose to add it to the array, you need to decide the following:

If that function gets modified, do you need your effect to run again?

If this is true, simply add it to the dependency array and React will take care of re-running your effect every time that function changes.

If this is not true, wrap your function into a useCallback so you can keep its reference the same across renders. You can also add a dependency array to the useCallback to control when the function needs to be recreated, or not.

EXTRA The function needs to be recreated, but you don't want to re-run.

  • Add some variable using useRef() to keep track of whether the effect has run once, and write a check into your effect to stop the effect if it's has run before. Like:
const effectHasRun_ref = useRef(false);
useEffect(()=>{
  if (effectHasRun_ref.current === true) {
    return;
  }
  else {
    // RUN YOUR EFFECT
    effectHasRun_ref.current = true;
  }
},[yourFunction]);
1
  • 1
    Two things I wonder about this: 1) How does this help with the <Button onClick={() => myFunction()/> example? 2) Is this any different than using a regular variable as opposed to useRef?
    – paddotk
    Commented Dec 7, 2019 at 19:38
3

So it seems like your aim is to keep your function inside your component and

  1. You don't want to move it inside useEffect since you want to use it elsewhere
  2. You don't want to move it outside your function since you want to avoid passing parameters from the component

In that case you i think the best solution is to use the useCallback hook as shown below


function YourComponent(props){

  const [stateItem, setStateItem] = useState(0);

  //wrap your logic in useCallback hook
  const myFunction = React.useCallback(
    () => {

      //if you use any dependencies in this function add them to the deps array of useCallback
      //so if any of the dependencies change thats only when the function changes

      return 'hello'
    }, [deps])

    useEffect(() => { 
       if(condition) {
          myFunction();
       }

    //add your function to the dependency array as well
    //the useCallback hook will ensure your function is always constant on every rerender thus you wont have any issues by putting it in the deps array, besides the #1 rule is NEVER LIE ABOUT YOUR DEPENDENCIES
    //the function only changes if the dependencies to useCallback hook change!!
    }, [stateItem, myFunction ])

   return (
     <Button onClick={() => myFunction()} />
   );
}


The useCallback hook will ensure your function is always constant on every rerender thus you wont have any issues by putting it in the deps array. the function only changes if the dependencies to useCallback hook change. By doing this we keep the golden rule of hooks which is NEVER LIE ABOUT YOUR DEPENDENCIES. Hope that helps. You might want to read this Blog Post By Dan Abramov

0

I would suggest you not to use the useEffect at all, as far as I understood, you want to call a certain function whenever a certain state was updated. For this, I would suggest you rather to write a custom function which will be called on the spot where it would be updated (for example an Input).

Now you could just call this function and update your state, since you know this function will only be called when only this particular state is about to be updated and then you can call your other function afterwards.

If you have something like a changeHandler you could also do it in there but I would rather suggest to write a custom function.

Small example code:

const [stateItem, setStateItem] = useState(0);

const myFunction = () => {
   // do something
};

const myOtherFunc = (value) => {
   setStateItem(value);

   if (condition) {
      myFunction();
   }
};

I hope I understood your problem correctly and this was helpful.

2
  • What I meant is, that you would call your function in for example a onChange function for this state and add your additional logic in there, this would then always run whenever you updated the state right after without needing the actual useEffect. But if you need this function also called in the initial render, then I understood your problem wrong.Otherwise, like said, I would recommend to remove the useEffect completly and put your logic in the change handler if there is a possibility like this.
    – Emre
    Commented Dec 8, 2019 at 20:14
  • Right, I see, you mean calling the myOtherFunction from anywhere where I now have setStateItem I guess. The problem with that though, which I guess is why the useEffect exists in the first place, is that setState functions run asynchronously. Therefore myFunction might run before the setstate has completed the update in your example.
    – paddotk
    Commented Dec 14, 2019 at 21:43
-1

TLDR: Add myFunction to dependency array like below

React useEffect has thing called dependency array what this does basically helps you and react to know when to re run the effect. Basically you should put everything that is defined outside the effect.

In this effect you are putting stateItem as a dependency of this effect this means that every time it changes react will re run this effect. Now as you might have guess you are using myFunction which is as well defined outside the effect, which means that react should know when that updates so it is aware. To fix this warning just put the function has a item in the the dependency array like this.

const [stateItem, setStateItem] = useState(0);

useEffect(() => {
  if (condition) {
    myFunction();
  }
}, [stateItem, myFunction]);

const myFunction = () => {
  return 'hello';
}
1
  • 4
    I suspected from the warning message that this is what React suggests doing. However, with functions specifically I wonder if that makes sense, since functions don't change/update and therefore would be tracked for no other reason than to surpress the warning..
    – paddotk
    Commented Nov 29, 2019 at 13:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.