Skip to content

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

### Why must I use same function reference??

removeEventListener requires exact same reference passed to addEventListener. Inline arrow creates new reference each render.

Should I always use React synthetic events??

React synthetic events handle most cases and auto-cleanup. Use addEventListener for window/document events or unsupported events.

How to pass options to addEventListener??

Third argument: window.addEventListener('scroll', handler, { passive: true }). Cleanup must pass same options.

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