Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React useEffect missing dependency for a function?

useEffect(() => {
    calculateTip();
  }, [bill, tipPercentage, numberOfPeople]);

  const calculateTip = () => {
    const tip = ((tipPercentage / 100) * bill).toFixed(2);
    const tipPerGroup = ((tipPercentage / 100) * bill * numberOfPeople).toFixed(
      2
    );
    setTipPerGroup(tipPerGroup);

    setTip(tip);
  };

I get an error:

React Hook useEffect has a missing dependency: 'calculateTip'. Either include it or remove the dependency array

Why does useEffect need to have a function in its dependency array? I mean the function never changes, it is the same same function, why does React force me to write it inside the dependency array?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Why does useEffect need to have a function in its dependency array. I
mean the function never changes . It is the same same function why
does react force me to write it inside the dependency array?

If that function is defined inside the component then it is not the same function, on the contrary it is re-created on each render. But that is not much related to the reason for the warning.

The reason why that warning asks you to put the function as dependency is the same as for other variables. The function itself may be referencing some variables which may become stale.

But when you add that function as dependency you may get another warning that dependencies change too often, in that case one option is to wrap that function into useCallback.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading