Skip to content

useEffect cleanup missing causes memory leak

Quick summary

Your useEffect sets up a timer or subscription but has no cleanup return — the resource keeps running after the component unmounts.

Why this happens

  • The effect creates a setInterval, setTimeout, or event listener but does not return a cleanup function

  • The cleanup function is missing or does not properly cancel the timer or remove the listener

  • An async operation started in the effect completes after unmount and tries to update state on an unmounted component

Minimal example

✗ Broken code
function Timer() {
  const [count, setCount] = useState(0);
  useEffect(() => {
    setInterval(() => setCount(c => c + 1), 1000); // no cleanup!
  }, []);
  return <div>{count}</div>;
}
✓ Fixed code
function Timer() {
  const [count, setCount] = useState(0);
  useEffect(() => {
    const id = setInterval(() => setCount(c => c + 1), 1000);
    return () => clearInterval(id); // cleanup on unmount
  }, []);
  return <div>{count}</div>;
}

Returning clearInterval(id) as the cleanup function stops the interval when the component unmounts, preventing the memory leak.

How to diagnose

  • Check the useEffect for a return statement that cleans up resources (clearInterval, removeEventListener, abort)

  • Look for React warnings about state updates on unmounted components or memory leak warnings

  • Use the React DevTools Profiler to check if effects are properly cleaned up on unmount

How to fix

  • Return a cleanup function from useEffect that clears timers, removes listeners, or aborts fetches

  • Use an AbortController to cancel in-flight fetch requests when the component unmounts

  • Use a ref or flag to check if the component is still mounted before updating state in async callbacks

How to prevent

  • Always return a cleanup function from useEffect when you set up any side effect resource

  • Use AbortController for fetch calls in effects and abort them in the cleanup function

Related Resources

Related Glossary

Related Lessons

← Back to language