DEV Community

Cover image for Cleanup Function on useEffect (Bite-size article)
koshirok096
koshirok096

Posted on

Cleanup Function on useEffect (Bite-size article)

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 memory leaks and unnecessary resource consumption.

The useEffect hook's cleanup function is used to clean up previous side effects when components are unmounted or re-rendered. 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 about the second argument on useEffect. If you are interested in it, please refer to that as well.

Image description

Case Study #1

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

  fetchData();

}, []);
Enter fullscreen mode Exit fullscreen mode

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.

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');
  };
}, []);
Enter fullscreen mode Exit fullscreen mode

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

Case Study #2

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

  return () => {
    console.log('Case Study #2');
  };
}, []);
Enter fullscreen mode Exit fullscreen mode

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

The correct version is like this:

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

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

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!

Top comments (0)