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

Time:05-30

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.

CodePudding user response:

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).

CodePudding user response:

It won’t be stale within the effect, but the effect won’t re-run when bar changes.

CodePudding user response:

Here you should understand when useEffect will work,

useEffect(() => { computation(foo, bar) } ) -> Will execute when any of the state in the component changes.

useEffect(() => { computation(foo, bar) }, [foo]) -> Will execute while mounting and during the 'foo' state changes.

useEffect(() => { computation(foo, bar) }, []) -> Will execute only while the component is mounting for the first time.

So if you don't include the dependency. The useEffect will be called every time any state of the component changes.

  • Related