DEV Community

SATHISHKUMAR R
SATHISHKUMAR R

Posted on

What is a Cleanup Function in React?

A Cleanup Function is a function inside useEffect that cleans up or stops previous operations when they are no longer needed.
Cleanup function helps us stop timers, remove event listeners and avoid unnecessary operations.

Syntax
useEffect(() => {

return () => {
};

}, []);

Here, return () => {} is the cleanup function.

When does Cleanup Function run?

There are 3 important situations:

Unmounting: When a component is removed from the screen.
Updating dependencies: Before the effect runs again because a dependency changed.
Development Strict Mode: React may run an extra setup and cleanup cycle to check your effect.
Example:
setInterval

import { useEffect } from 'react';

function App() {

useEffect(() => {

    const timer = setInterval(() => {
        console.log("Hello React");
    }, 1000);

    return () => {
        clearInterval(timer);
        console.log("Timer Stopped");
    };

}, []);

return <h1>Hello!</h1>;
Enter fullscreen mode Exit fullscreen mode

}

export default App;

Step-by-step explanation:

  1. Component mounts.
  2. useEffect runs.
  3. setInterval starts.
  4. Every 1 second, "Hello React" prints.
  5. Component unmounts.
  6. Cleanup function runs.
  7. clearInterval(timer) stops the timer.

  8. Example:
    Event Listener:

useEffect(() => {

function handleClick() {
    console.log("Clicked!");
}

window.addEventListener("click", handleClick);

return () => {
    window.removeEventListener("click", handleClick);
};
Enter fullscreen mode Exit fullscreen mode

}, []);

Why cleanup?

Without cleanup, the event listener may remain active even after the component is removed.

Top comments (0)