user11092881
user11092881

Reputation:

useEffect has a missing dependency that's a const function

useEffect(() => {
    let interval = null;
    if (isOn) {
      interval = setInterval(() => {
        counting();
      }, 1000);
    } else {
      clearInterval(interval);
    }
    return () => clearInterval(interval);
}, [isOn, currentTimeMs]);


const counting = () => {
    setCurrentTimeMs(currentTimeMs + 1);
};

I thought the dependency of useEffect only accepted variables, but it also asks me to put a function that's a const? Why is that? Is that an error with webpack or something?

React Hook useEffect has a missing dependency: 'counting'. Either include it or remove the dependency array react-hooks/exhaustive-deps

I also am getting another warning:

The 'counting' function makes the dependencies of useEffect Hook (at line 39) change on every render. Move it inside the useEffect callback. Alternatively, wrap the 'pace' definition into its own useCallback() Hook react-hooks/exhaustive-deps

I thought I was already calling inside the useEffect callback. Can someone explain? The documentation doesn't say much about useEffect and its callback.

Upvotes: 1

Views: 1512

Answers (1)

Drew Reese
Drew Reese

Reputation: 202801

Variables that are declared const are still variables. In this case you redefine counting each render cycle, but being const means the variable counting can't be reassigned a value during a render cycle. Because you redefine it each render cycle is the reason you see the second warning.

If nothing else calls counting then just move it inside the effect. This removes the need to include it in the dependency array, and only gets defined when the effect's callback triggers.

useEffect(() => {
  let interval = null;

  const counting = () => {
    setCurrentTimeMs(currentTimeMs => currentTimeMs + 1);
  };

  if (isOn) {
    interval = setInterval(counting, 1000);
  } else {
    clearInterval(interval);
  }
  return () => clearInterval(interval);
}, [isOn]);

Note 1: I converted updating setCurrentTimeMs to use a functional state update since state depends on previous state.

Note 2: I also removed currentTimeMs from the dependency array so you don't set more than one interval each time state updates when isOn is true. [edit] Actually, this is ok since the cleanup function handles clearing the interval set from previous cycle. Should still remove currentTimeMs though as it isn't necessary.

Edit toggleable set interval effect

Upvotes: 2

Related Questions