Skip to content

How to Fix React Unmount Memory Leaks

DodaTech Updated 2026-06-26 1 min read

The Problem

In this quick-fix, you'll learn how to clean up subscriptions timers and listeners on unmount. This matters because uncleared resources cause memory leaks that crash browser tabs. In real-world applications, this pattern appears in real-time dashboards with WebSockets interval polling scroll listeners.

The Wrong Way

function LiveTimer() {
  const [s, setS] = useState(0);
  useEffect(() => { setInterval(() => setS(x=>x+1), 1000); }, []);
  return <div>{s}s</div>;
}
function App() {
  const [show, setShow] = useState(true);
  return <>{show && <LiveTimer />}<button onClick={()=>setShow(false)}>Unmount</button></>;
}
After unmount interval keeps running -- memory leak

The Right Way

function LiveTimer() {
  const [s, setS] = useState(0);
  useEffect(() => { const id = setInterval(() => setS(x=>x+1), 1000); return () => clearInterval(id); }, []);
  return <div>{s}s</div>;
}
After unmount interval cleared -- no leak

Prevention

  • Return cleanup from useEffect for subscriptions timers listeners
  • Use clearInterval clearTimeout removeEventListener
  • Use AbortController for fetch

FAQ

### How to detect memory leaks??

Use Chrome DevTools Performance heap snapshots before/after mount/unmount. If memory doesnt return to baseline there is a leak.

Does useRef cause memory leaks??

No ref values are GCd on unmount. But if ref holds subscription reference not cleaned up the objects can leak.

What about 3rd party library subscriptions??

Wrap in useEffect with cleanup. Most libraries support teardown via close disconnect or unsubscribe.

This guide is brought to you by DodaTech — built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro