DEV Community

Cover image for Developers might be using useEffect wrong this whole time
Sanchit Bajaj
Sanchit Bajaj

Posted on

Developers might be using useEffect wrong this whole time

Hi there everyone 👋, if you're a React Developer then there might be the case that you're misusing the useEffect hook in one way or another. I also have been misusing the react useEffect() hook for a very long time.

So in this blog, I am going to help developers avoid bad use cases with useEffect and how you can completely avoid that as a react developer whether you're a beginner or an advanced developer.

What is wrong?

As react developers, we all worked with useEffect tons and tons of times but have we ever thought about what is useEffect, what it does and whether are we actually using the useEffect the right way or maybe aren't we misusing it? Maybe we are not using useEffect correctly in the right place, it should be used because as we all know we use it for pretty much everything as React Developers for fetching data, handling events, transforming data, large components or even implementing advanced logic.

If you go to the new React Documentation which is completely a re-writing of the old react documentation and look for the useEffect hook, it says

"useEffect is a React Hook that lets you synchronize a component with an external system".

So from this perspective, it means that it is meant for synchronization and not for handling events or transforming data. It is only used for synchronization with an external component.

By synchronization, it means that useEffects are meant to specify side effects that are caused by rendering itself, rather than by a particular event.

How should I avoid them?

To avoid synchronization issues, you can try to minimize your logic like calculation, checking the states, error handling, etc. outside of useEffect hook or you can make go with the declarative paradigm and define all the logic of calculation or transforming data or event handling into different files.

To know more about this, here is the detailed video to which you can refer

Thank you! for reading, please leave your comments if any ✌️

Don't forget to bookmark this blog for the future 📌

Connect with the author:

References

Top comments (1)

Collapse
 
brense profile image
Rense Bakker

The way I usually look at useEffect is that its a hook to do anything that is not part of the react component lifecycle (mounting, rendering, updating, unmounting). That includes API requests, Executing initialization/config code for external libraries that are not written in React, adding window or document event listeners or listening/subscribing to websockets or other async events (always with cleanup function).