Search code examples
reactjsuse-effect

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?


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.