DEV Community

vishwa v
vishwa v

Posted on

react-4

What is Cleanup

When you use useEffect, sometimes you set up things that live outside your component:

Event listeners (window.addEventListener)

Subscriptions (like WebSocket or Firebase)

Timers (setInterval, setTimeout)

External resources (like API connections)

If you don’t remove them when the component unmounts, they keep running in the background β†’ causing bugs, memory leaks, or duplicate behavior.

How Cleanup Works

React lets you return a function inside useEffect.
That function runs:

Before the component unmounts (to clean up resources).

Before the effect re-runs (to reset old setup before applying new one).

import React, { useState, useEffect } from "react";

function TimerExample() {
  const [count, setCount] = useState(0);

  useEffect(() => {

    const intervalId = setInterval(() => {
      setCount(prevCount => prevCount + 1);
    }, 1000);


    return () => {
      clearInterval(intervalId);
      console.log("Interval cleared!");
    };
  }, []); 

  return (
    <div>
      <h1>Timer Count: {count}</h1>
    </div>
  );
}

export default TimerExample;

Enter fullscreen mode Exit fullscreen mode

Top comments (0)