DEV Community

Cover image for Need of useEffect Cleanup Function
Sanchit Bajaj
Sanchit Bajaj

Posted on • Edited on

Need of useEffect Cleanup Function

Hello fellow developers, in this blog you will learn about the cleanup function of useEffect() which I feel that many new react developers ignore. Many new developers think that it is too complex to understand and skip over that part but it is one of the most essential parts while learning about the hooks.

The general syntax of writing a useEffect() hook in react is:

import {useEffect} from "react";

function App() {
    // some logic....

    useEffect(() => {
        // synchronization code...

        // cleanup function...
        return () => {};
    }, []); // dependency array
    // some logic....    
}
Enter fullscreen mode Exit fullscreen mode

But many people ignore the clean-up function which causes several problems in synchronization.

Problem.

Let's say you created a state and a useEffect() hook that updates the state every 1000 milliseconds or 1 second. The below code will work perfectly fine.

image 1

But if you add something after the use of your state variable, the code will not work as intended. The below code skips some numbers while updating the number every second.

image 2

This is because, in every render, we create another interval without clearing the previous one. And without clearing them, you can notice many intervals have been created.

Solution.

To fix this problem, we can use the clean-up function. Let me explain how it works. So when React DOM loads the first time, it renders the component along with the useEffect() hook and when the state updates inside useEffect(), a cleanup function is called before updating the DOM. With this, the previous intervals are cleared and new ones get mounted.

image 3

If you're familiar with the Class-Based React Components, there are some LifeCycle Methods to perform this same functionality. The methods ComponentDidMount() and ComponentWillUnmount() will do the same functionality.

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

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

Connect with the author:

Top comments (0)