Sanchit Bajaj
Sanchit Bajaj's blog

Follow

Sanchit Bajaj's blog

Follow

Need of useEffect Cleanup Function

Sanchit Bajaj's photo
Sanchit Bajaj
ยทMar 22, 2023ยท

2 min read

Need of useEffect Cleanup Function
Play this article

Table of contents

  • Problem.
  • Solution.

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....    
}

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.

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.

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.

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:

Did you find this article valuable?

Support Sanchit Bajaj by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
ย 
Share this