Cleanup for Event Listeners
What you'll learn: How to properly attach and detach event listeners in useEffect to prevent memory leaks and duplicate listeners.
Why Event Listeners Need Cleanup
When you add an event listener in an effect (like listening to window scroll or resize), that listener stays attached even if your component re-renders or unmounts. Without cleanup, you create memory leaks—old listeners pile up, consuming resources and potentially triggering callbacks for components that no longer exist.
The Standard Pattern
The pattern is simple but critical:
- In the effect body: Add the event listener
- In the cleanup function: Remove that exact same listener
useEffect(() => {
const handleResize = () => {
console.log('Window resized!');
};
// Attach listener
window.addEventListener('resize', handleResize);
// Return cleanup function
return () => {
// Detach listener
window.removeEventListener('resize', handleResize);
};
}, []); // Empty array: set up once on mount, clean up on unmount
Why This Works
When your component unmounts (or before the effect re-runs), React calls your cleanup function. This ensures the listener is removed at the right time, preventing:
- Multiple identical listeners after re-renders
- Listeners trying to update state in unmounted components
- Memory not being freed
Think of it like subscribing to a magazine: you sign up (addEventListener), then you cancel (removeEventListener) when you move away. Without canceling, magazines keep arriving forever.
The Critical Detail
You must remove the exact same function reference you added. That's why we define handleResize inside the effect—so both addEventListener and removeEventListener reference the same function.
Key Takeaway: Always pair addEventListener in an effect with removeEventListener in the cleanup function to prevent memory leaks and duplicate listeners.