Search code examples
javascriptreactjsuse-effect

If I don't include a dependency in the useEffect array, will it be stale inside the closure?


Example:

const [foo, setFoo] = useState(0)
const [bar, setBar] = useState(0)

useEffect(() => { computation(foo, bar) }, [foo])

Will the value of bar inside the useEffect closure be stale? I'm asking because in one of my applications, I forgot to include the bar in the deps array and it seemed like it was still up to date.


Solution

  • Kind of, but not exactly. Staleness won't really be an issue, but whether the hook runs at all will be, because you're using useEffect rather than something like useCallback.

    Using [foo] means that it'll run when foo changes. If your other code is set up that whenever bar changes, foo has or will also be changed as well, then when the component re-renders, the new values of both will then be seen by the effect hook.

    But if you change bar without changing foo, the effect won't run at all.

    You would have a stale closure problem, if bar changed when foo didn't, if you were using useCallback or useMemo, among others, because those save a value in an outer variable (which can then be called or passed to other components).