Should you pass setter functions into the dependency array of a React hook?

Viewed 2062

Recently I saw a few examples of passing setter functions into hook dependency arrays in my coworkers' React code, and it doesn't look right to me. For example:

const MyComponent = () => {
  const [loading, setLoading] = useState(true);
  useEffect(() => {
    doSomeBigLongNetworkRequest();
    setLoading(false);
  }, [setLoading, /* other deps */]);
  // ...
}

My feeling is that they have misunderstood the purpose of the dependency array, which, as I understand it, is to indicate which pieces of state to monitor so that the hook can fire again when they change, not to simply indicate that the hook needs to use the setLoading function. And since the setLoading function never actually changes, including it in the dependencies does nothing.

Am I correct, or does including the setter in the array make sense somehow? My other thought was that maybe this was just a linter error, since the linter cannot recognize that the function is a setter, and thinks it might change.

I should also add that in the instances I've seen, they've included the setter but not the variable. So in the example above, setLoading, but not loading would be in the dependency array, and the hook does not actually need the value of loading.

1 Answers

Yes, you are right there is no need to include them based on docs:

React guarantees that setState function identity is stable and won’t change on re-renders. This is why it’s safe to omit from the useEffect or useCallback dependency list.

In general again based on docs the recommendation is that:

all values from the component scope (such as props and state) that change over time and that are used by the effect should be in dependencies

Otherwise, the code will reference stale values from previous renders.

Related