ReactFeb 6, 2025

What is the React useEffect cleanup function, and how it works?

Rahul Kumar
By Rahul Kumar
What is the React useEffect cleanup function, and how it works?

Detailed explanation about React’s useEffect cleanup function works.

What is the useEffect cleanup function?

The useEffect cleanup function in React is a function you return from inside your useEffect hook. It’s called automatically when your component unmounts, or just before the effect runs again, to clean up any ongoing side effects like intervals, subscriptions, or network requests.

useEffect(() => {
      // Your effect code (side effect)
      return () => {
        // Cleanup code runs before unmount or before next effect
      };
    }, [dependencies]);

Why do you need a cleanup function?

Without cleanup, lingering side effects (like timers, event listeners, or fetches) can cause memory leaks, bugs, or errors if they try to update state after your component has unmounted.

When does the cleanup function run?

  • When the component unmounts.
  • Before the effect runs again (if dependencies change).

Common use cases

  • Clearing setInterval or setTimeout
  • Aborting fetch requests with AbortController
  • Removing event listeners
  • Unsubscribing from WebSocket or data streams

Example: Cleaning up an interval

useEffect(() => {
      const intervalId = setInterval(() => {
        // Do something every second
      }, 1000);
      return () => clearInterval(intervalId); // Cleanup
    }, []);

Example: Cleaning up a fetch request

useEffect(() => {
      const controller = new AbortController();
      fetch(url, { signal: controller.signal })
        .then(...)
        .catch(...)
      return () => controller.abort(); // Cleanup
    }, [url]);
“Cleanup functions in useEffect help keep your React apps bug-free and performant by preventing unwanted side effects.”

Learn to use cleanup functions whenever you set up side effects in your components!

Rahul Kumar

About Rahul Kumar

Full Stack Developer with a passion for technology, JavaScript, and sharing knowledge on web development and computer science.