No need setFoo.
TODO: collapasable, copyable, download, etc
In React, if I let [foo, setFoo] = useState(null)
and then in useEffect(..., [foo, setFoo])
does it make sense to pass in setFoo? Or is that not needed?In React, when you use useState()
to create state in a functional component, it gives you a state variable (in your example, foo
) and a function to update that state variable (setFoo
). The update function (setFoo
) does not change between re-renders. This means that it is stable and does not need to be included in the dependency array of useEffect
or other React hooks like useMemo
or useCallback
.
The dependency array in a useEffect
hook is intended to list all values from the component scope (such as props and state variables) that change over time and on which the effect depends. Since setFoo
does not change, including it in the dependency array is unnecessary.
So, if your effect is solely using setFoo
to update the state and does not directly depend on the value of foo
, you do not need to include setFoo
in the dependency array. You would typically only include foo
if the effect needs to run when foo
changes.
Here's a simplified version:
let [foo, setFoo] = useState(null);
useEffect(() => {
// Code that only depends on `foo` and uses `setFoo` to update it
}, [foo]); // `setFoo` is not required here because it does not change
Including setFoo
in the dependency array does not cause any harm, but it does not follow the intended use of the dependency array and can lead to confusion about the dependencies of your effect. It's best practice to include only the values that the effect actually depends on to make your code clearer and to avoid unnecessary executions of the effect.
Related Chats
No need setFoo. 1.000
Use Effect vs Component Body 0.666
Memo Once, No Dependencies 0.649
Force Sync Read Atom. 0.553
Provider vs useAtom: when? 0.541
React TypeScript Component: Props & Render 0.490
Reset Saving State Strategically 0.479
Wrap in useCallback Hook 0.461
Jotai with React Query 0.455
Listen for Command+K. 0.451