Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In useEffect, what's the difference between providing no dependency array and an empty one?

I gather that the useEffect Hook is run after every render, if provided with an empty dependency array:

useEffect(() => {   performSideEffect(); }, []); 

But what's the difference between that, and the following?

useEffect(() => {   performSideEffect(); }); 

Notice the lack of [] at the end. The linter plugin doesn't throw a warning.

like image 930
Paul Razvan Berg Avatar asked Oct 27 '19 12:10

Paul Razvan Berg


People also ask

What happens if you don't use dependency array in useEffect?

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 does an empty useEffect do?

The empty array says “never re-create the closure, because this effect doesn't refer to any variables that will change”. With the empty array being passed, useEffect will hang on to the first function you pass it, which in turn will hang on to references to all the (maybe stale) variables that were used inside it.

What is the use of dependency in useEffect?

useEffect(callback, dependencies) is the hook that manages the side-effects in functional components. callback argument is a function to put the side-effect logic. dependencies is a list of dependencies of your side-effect: being props or state values.

Which lifecycle method does a useEffect with an empty dependency array replace?

The useEffect Hook allows us to replace repetitive component lifecycle code.


1 Answers

It's not quite the same.

  • Giving it an empty array acts like componentDidMount as in, it only runs once.

  • Giving it no second argument acts as both componentDidMount and componentDidUpdate, as in it runs first on mount and then on every re-render.

  • Giving it an array as second argument with any value inside, eg , [variable1] will only execute the code inside your useEffect hook ONCE on mount, as well as whenever that particular variable (variable1) changes.

You can read more about the second argument as well as more on how hooks actually work on the official docs at https://reactjs.org/docs/hooks-effect.html

like image 124
bamtheboozle Avatar answered Oct 08 '22 22:10

bamtheboozle