Cleanup Function on useEffect (Bite-size article)
Tags: react, beginners
Published: 2023-08-12 22:13:41

#Intro

Today I will write about Cleanup function on React **useEffect** hook.

The useEffect hook is used to perform side effects when components are mounted (displayed), updated (re-rendered), or unmounted (hidden). Common uses include retrieving data, listening for events, subscribing, and setting timers. 

However, proper **cleanup** is important because these side effects can cause <u>memory leaks</u> and <u>unnecessary resource consumption</u>.

The useEffect hook's cleanup function is used to <u>clean up previous side effects when components are unmounted or re-rendered</u>. This frees up resources and removes unnecessary listeners, thereby improving application performance and stability.

Starting in the next chapter, I will explain in detail with examples.

_Also, I have written an [article](https://dev.to/koshirok096/understand-the-second-argument-of-useeffect-bite-size-article-2mg2) about the second argument on useEffect. If you are interested in it, please refer to that as well._

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d443d2gs32i0h8nnko08.png)



#Case Study #1

```js
useEffect(() => {
  const fetchData = async () => {
    const response = await fetch('https://api.example.com/data');
    const jsonData = await response.json();
    setData(jsonData);
  };

  fetchData();

}, []);
```

In this example, data is retrieved from the external API and subscribed to in the useEffect callback function, but the data is not unsubscribed when the component is unmounted because a cleanup function is not provided.

```js
useEffect(() => {
  const fetchData = async () => {
    const response = await fetch('https://api.example.com/data');
    const jsonData = await response.json();
    setData(jsonData);
  };

  fetchData();
  // added
  return () => {
    console.log('Unsubscribing from data updates');
  };
}, []);
```

Adding the code as in the second one, will peform as a cleanup function.

#Case Study #2

```js
useEffect(() => {
  const intervalId = setInterval(() => {
    setTime(new Date());
  }, 1000);

  return () => {
    console.log('Case Study #2');
  };
}, []);
```

This is another example. In this example, the timer is being processed to update every second in the useEffect callback function. However, there is no cleanup function. So the timer is not stopped when the component is unmounted.

Before you see the answer, let's consider what is needed.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pvu8jomkweb9zc62i39m.png)


The correct version is like this:

```js
useEffect(() => {
  const intervalId = setInterval(() => {
    setTime(new Date());
  }, 1000);

  // cleanup
  return () => {
    // stop timer
    clearInterval(intervalId);
    console.log('Timer stopped');
  };
}, []);
```

In this new code, the timer set by the setInterval function is stopped by **clearInterval** in the cleanup function. This ensures that the timer is properly stopped when the component is unmounted, preventing unnecessary consumption of resources.

#Outro
The correct cleanup implementation will maintain the performance and stability of your application. I hope this article helps to you.

Thank you for reading!