1
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?

1
  • 1
    Because it doesn't match the heuristics used to decide whether or not this is something that changes. In fact, if that function definition is inside the component, it does change - you create a new function (albeit with the same logic inside) on every render. Commented May 27, 2022 at 14:29

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

8 Comments

Hey @GiorgiMoniava i have run into another error The 'calculateTip' function makes the dependencies of useEffect Hook (at line 28) change on every render. Move it inside the useEffect callback. Alternatively, wrap the definition of 'calculateTip' in its own useCallback() Any ideas?
@AmosMachora that message gives you two options for solving the problem - did you try either of them?
@jonrsharpe I honestly didn't understand anything that error said. I'm kind of a noob in react .
@AmosMachora Here is more reading: reactjs.org/docs/…
@AmosMachora one of those suggestions isn't specific to React. For the other did you consider reading about the useCallback hook?
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.