I saw someone use 0 instead of an empty array for the second argument in useEffect.
So instead of
useEffect(() => {
console.log('Run once');
}, []);
it was
useEffect(() => {
console.log('Run once');
}, 0);
It seems to have the same effect so I'm wondering why he used that?
An empty array is considered 0 depending on how you evaluate it. For instance [] == 0
is true, but [] === 0
is false. So maybe in this case there isn't a strict comparison under the hood and it does not matter if you use 0.
Just following the react docs i would use an empty array.
If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument. This tells React that your effect doesn’t depend on any values from props or state, so it never needs to re-run. This isn’t handled as a special case — it follows directly from how the dependencies array always works.
I'm wondering if 0
is a potentially more concise binary argument to use over []
, or if using 0
is a bad practice, or if it doesn't matter and []
is just a preferred React convention?
Thanks.