DEV Community

Cover image for React Tricks Miniseries 6: How to use useEffect properly
Uriel Bitton
Uriel Bitton

Posted on

React Tricks Miniseries 6: How to use useEffect properly

The useEffect hook in react is probably the most complex hooks to write correctly and understand properly.

Without going too much into the semantics of how useEffect works, i will offer a brief explanation just enough to demonstrate how to use it correctly.

useEffect is a react function that runs the code inside it asynchronously. But by default it is not asynchronous. By default it runs your code when the component mounts and it runs it only once. The dependency array that you see at the end is there to say "whatever variable(s) you put inside, i will execute the entire code inside me again, every time that variable(s) changes value". This is where it becomes asynchronous, only once you put a variable in the dependency array.

useEffect(() => {
  //get posts info from database
  //get posts info again everytime a new comment is added/edited
},[comments]) 
Enter fullscreen mode Exit fullscreen mode

By putting the variable comments (which can contain the posts comments array) inside the dependency array, we tell react we want to refetch the posts data, everytime a comment is added or edited.

Now there are 2 concepts many developers leave out or are not aware of.

Cleanup

Cleanup functions are meant to unsubscribe from the useEffect. Meaning when the component unmounts from the virtual dom, we want to stop fetching the posts data. If we don't do anything about it, react will run into errors, and warn you in the console about unsubscribing from the useEffect. So to solve that we can use a simple cleanup function.

This is where we can use a nifty trick. Instead of figuring out what to return to stop the subscription, we can simply return our original code in the useEffect and it will automatically get destroyed everytime the component unmounts.

useEffect(() => 
  //get posts info from database
,[comments]) 
Enter fullscreen mode Exit fullscreen mode

Note how by removing the curly braces, effectively returning the original code, react will unsubscribe any listeners inside the useEffect. No need for returns. Our code is kept cleaner and shorter.

Conclusion

By returning our original code inside our useEffect, we can achieve a cleaner cleanup and unsubscribe listeners inside our useEffect.

Did you know this trick or just learned it now? Let me know in the comments!

Discussion (3)

Collapse
getsetgopi profile image
Gopinath Prasanna

I always write return to cleanup and never knew this trick. Will try it out in my next project. Thanks for sharing!!

Collapse
theeasydev profile image
Uriel Bitton Author

Its my pleasure :)