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
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