Mid-Level Hooks 5 min read

Explain useEffect Cleanup Functions in React

The Interview Question

What is a useEffect cleanup function, when does it run, and why is it important?

Expert Answer

A useEffect cleanup function is the function you return from inside a useEffect callback. React calls this cleanup function before the component unmounts and before re-running the effect if its dependencies change. This is critical for preventing memory leaks — if your effect sets up a subscription, starts a timer, or adds an event listener, the cleanup function is where you tear it down. Without cleanup, you end up with stale listeners firing on unmounted components, WebSocket connections that never close, and intervals that keep running in the background.

Key Points to Hit in Your Answer

  • Cleanup runs before every re-execution of the effect, not just on unmount
  • Common use cases: clearing timers, canceling API requests, removing event listeners, closing WebSocket connections
  • If you forget cleanup on a subscription, you get the classic 'Can't perform a React state update on an unmounted component' warning
  • AbortController is the modern pattern for cleaning up fetch requests

Code Example

useEffect(() => {
  const controller = new AbortController();
  
  fetch('/api/data', { signal: controller.signal })
    .then(res => res.json())
    .then(data => setData(data))
    .catch(err => {
      if (err.name !== 'AbortError') throw err;
    });

  // Cleanup: cancel the request if component unmounts
  return () => controller.abort();
}, []);

What Interviewers Are Really Looking For

Interviewers want to see that you understand the lifecycle implications — that cleanup isn't just about unmounting but runs between re-renders too. Bonus points for mentioning AbortController for fetch cleanup and explaining the stale closure pitfall.

Practice This Question with AI Grading

Reading about interview questions is a start — but practicing with real-time AI feedback is how you actually get better. Goliath Prep grades your answers instantly and tells you exactly what you're missing.

Start Practicing Free →