DEV Community

Don't use useEffect unnecessarily

Remon Fawzi on January 10, 2023

In this post We'll prove that in 90% of our components we don't need to write a useEffect ... First question, When does useEffect run? ...
Collapse
 
eduardojm profile image
Eduardo Oliveira •

The title of this article can be changed from "Don't use useEffect" to "Don't create dependent states on React"... useEffect should be used to handle side effects of some cases, like the useOutsideClick hook of the chakra-ui package.

Collapse
 
rem0nfawzi profile image
Remon Fawzi • • Edited

Right, I just wanted to say We shouldn't use useEffect when what we want could be achieved without it.
Thank u!

Collapse
 
eduardojm profile image
Eduardo Oliveira •

The wrong use of the useEffect is really a great problem in React (and i got some of it in legacy projects that i work :/)

Thread Thread
 
rem0nfawzi profile image
Remon Fawzi •

We all did that 😅

Collapse
 
brense profile image
Rense Bakker •

Indeed! If you need to set state based on changes in component state/props, you should use the useMemo hook. useEffect is only for triggering side effects outside of the scope of the component. Like adding event listeners to the window for example or interacting with a library that was not specifically written for React.

Collapse
 
rem0nfawzi profile image
Remon Fawzi •

Exactly, Thank u!

Collapse
 
manuartero profile image
Manuel Artero Anguita 🟨 •

+100, useEffect() should only be used for fetch the initial data (and in some extreme extra situations)

useEffect(() => {
  api.fetchItems().....
}, [])
Enter fullscreen mode Exit fullscreen mode

good post!

Collapse
 
rem0nfawzi profile image
Remon Fawzi •

Thank u!

Collapse
 
hpgriff profile image
Hp.Griff •

Oh oh. I need to make some changes on my code... I'm using useEffect way too much. Thanks for the share !

Collapse
 
rem0nfawzi profile image
Remon Fawzi •

You're welcome

Collapse
 
sanoshyadav979439 profile image
Santosh Yadav •

You can use React.memo to not rerender the component itself in case of no prop change instead of useMsmo just for calculating initials

Collapse
 
rem0nfawzi profile image
Remon Fawzi •

Yes exactly