How to Fix Event Listener Memory Leaks
DodaTech
Updated 2026-06-26
1 min read
The Problem
In this quick-fix, you'll learn how to correctly add and remove DOM event listeners. This matters because listeners not removed accumulate causing memory leaks. In real-world applications, this pattern appears in scroll animations resize handlers keyboard shortcuts.
The Wrong Way
function ScrollPosition() {
const [scrollY, setScrollY] = useState(0);
useEffect(() => { window.addEventListener('scroll', () => setScrollY(window.scrollY)); }, []);
return <div>Scrolled: {scrollY}px</div>;
}
Listener never removed -- duplicate listeners accumulate on remount
The Right Way
function ScrollPosition() {
const [scrollY, setScrollY] = useState(0);
useEffect(() => {
const handleScroll = () => setScrollY(window.scrollY);
window.addEventListener('scroll', handleScroll);
return () => window.removeEventListener('scroll', handleScroll);
}, []);
return <div>Scrolled: {scrollY}px</div>;
}
Listener added on mount removed on unmount -- no leaks
Prevention
- Store handler in variable for cleanup
- Pass exact same function reference to add/removeEventListener
- Inline arrows cannot be removed
- Use passive:true for scroll/touch events
FAQ
This guide is brought to you by DodaTech -- built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
← Previous
How to Fix useEffect Dependency Array Warnings
Next →
How to Fix useEffect Interval Timer Issues
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro