Skip to content

Bug: useEffect cleanup not running

Error message

                Cleanup function from useEffect is not being called
              

Quick summary

The cleanup function returned from useEffect is not running, usually because it wasn't returned or the effect has wrong dependencies.

Why this happens

  • Forgot to return the cleanup function from useEffect

  • Returned the cleanup call instead of the function: return cleanup() instead of return cleanup

  • Effect dependencies prevent re-runs where cleanup would fire

Minimal example

✗ Broken code
useEffect(() => {
  const id = setInterval(tick, 1000);
  clearInterval(id); // Called immediately, not on cleanup!
}, []);
✓ Fixed code
useEffect(() => {
  const id = setInterval(tick, 1000);
  return () => clearInterval(id); // Returned for cleanup
}, []);

The cleanup must be returned as a function. React calls it on unmount (or before the next effect), not immediately.

How to diagnose

  • Check that useEffect returns a function (not calls it)

  • Add console.log in both the effect and cleanup to verify execution

  • Check the dependency array — cleanup runs before the next effect or on unmount

How to fix

  • Return the cleanup function: return () => { clearInterval(id); }

  • Ensure the effect has correct dependencies so it re-runs when needed

  • For one-time effects with [] deps, cleanup runs only on unmount

How to prevent

  • Always return a cleanup function when setting up subscriptions, timers, or listeners

  • Test unmount behavior to verify cleanup runs

Related Resources

Related Glossary

Related Lessons

← Back to language