DEV Community

Cover image for Why we use empty array with UseEffect

Why we use empty array with UseEffect

Clara Situma on December 08, 2022

If you do not pass an empty array as an argument to useEffect, the effect will run on every render of the component. This means that any code ins...
Collapse
 
brense profile image
Rense Bakker

Bonus points if you also add a cleanup to your useEffect, to cancel the request when the component gets unmounted during fetching. In your current code the state update will produce an error if the component gets unmounted during fetching (cant update state of unmounted component).

Collapse
 
csituma profile image
Clara Situma

Thank you, that's a great addition

Collapse
 
csituma profile image
Clara Situma

what do you think about this dev.to/csituma/do-i-need-to-use-cl...

Collapse
 
brense profile image
Rense Bakker

I mostly agree with that, except that you should also cleanup if you do delayed state updates in your useEffect, to avoid updating state on unmounted components (which will result in an error).

Collapse
 
ritikbanger profile image
Ritik Banger

Providing no dependency in the useEffect give sideEffects and introduce bugs. Always, Always give the dependencies required by useEffect. By using empty array you can get your desired result but it will definitely introduce bug and hard to maintain the code in long run.

Collapse
 
csituma profile image
Clara Situma

This is correct.

However in instances where there are no dependencies, an empty array is okay,
Don't you agree?

Collapse
 
ritikbanger profile image
Ritik Banger

Could you give an example where the instance does not have any dependency? Even if you use a variable/function, you have to give a dependency.

Thread Thread
 
csituma profile image
Clara Situma

Hmm...

A simple fetch?

useEffect(() => {
fetch("pokeapi.co/api/v2/type/3")
}, []);

Thread Thread
 
ritikbanger profile image
Ritik Banger • Edited

In this example, the useEffect will ask for the dependency of fetch function.

The corrected code:

useEffect(() => {
fetch("pokeapi.co/api/v2/type/3")
}, [fetch]);
Enter fullscreen mode Exit fullscreen mode

If you use the empty array as a dependency and if you have any linter, you will surely get an error/warning based on the setup.

Thread Thread
 
csituma profile image
Clara Situma

In your example, using fetch as dependency is unnecessary and will infact bring up a warning(mutating it can't cause a re-render because it will be recognised as an Outer scope value )

You should try run the code