Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Hooks - 0 vs. empty array as second argument in useEffect

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.

React docs:

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.

like image 889
StefanBob Avatar asked Jul 07 '20 18:07

StefanBob


People also ask

Why do we use empty array in useEffect?

Empty dependency array So what happens when the dependency array is empty? It simply means that the hook will only trigger once when the component is first rendered. So for example, for useEffect it means the callback will run once at the beginning of the lifecycle of the component and never again.

What is the second argument in useEffect hook?

The useEffect Hook allows you to perform side effects in your components. Some examples of side effects are: fetching data, directly updating the DOM, and timers. useEffect accepts two arguments. The second argument is optional.

What if dependency array is empty in useEffect?

If it's empty ( [] ), the effect runs once, after the initial render. It must — or as we'll see later, should — contain the list of values used in the effect. The effect runs after any of these values changes (and after the initial render). The array of dependencies is not passed as argument to the effect function.


1 Answers

This is the signature for the useEffect function

export function useEffect(
  create: () => (() => void) | void,
  deps: Array<mixed> | void | null,
): void {
  const dispatcher = resolveDispatcher();
  return dispatcher.useEffect(create, deps);
}

There you can see it only accepts an Array, void or null, so the correct answer to your question is to always send an array if you want to run it just once

like image 165
ludwiguer Avatar answered Sep 22 '22 06:09

ludwiguer