Course contentsShow
← React
Lesson 397 of 2,39611. useState Patterns and PitfallsFree lesson

Stale State in Event Listeners

Why addEventListener callbacks see old state and how cleanup prevents accumulating stale listeners.

Stale State in Event Listeners

You'll learn why addEventListener callbacks often see outdated state values and how proper cleanup prevents these bugs.

The Problem

When you add an event listener inside a React component (like a keyboard handler on window or document), that listener's callback function captures the state value from when it was created. Unlike React's own event handlers (like onClick), these listeners don't automatically see updated state values on re-renders.

const [count, setCount] = useState(0);

useEffect(() => {
  const handleKeyPress = () => {
    console.log(count); // Always logs 0!
  };
  
  window.addEventListener('keydown', handleKeyPress);
  
  // Missing cleanup = stale listener accumulates
}, [count]);

Every time count changes, a new listener is added, but the old ones remain attached. The first listener forever sees count = 0, the second sees count = 1, and so on.

The Solution Pattern

Always return a cleanup function that removes the listener, and use functional updates when you need to modify state:

useEffect(() => {
  const handleKeyPress = () => {
    setCount(prev => prev + 1); // Functional update sees current value
  };
  
  window.addEventListener('keydown', handleKeyPress);
  
  return () => {
    window.removeEventListener('keydown', handleKeyPress);
  };
}, []); // Empty deps: add listener once, clean up on unmount

The cleanup removes the old listener before adding the new one (when deps change), preventing accumulation. The functional update ensures you always work with the latest state value.

Key Takeaway: Event listeners capture state from their creation time; always clean them up with removeEventListener in your effect's return function, and use functional updates (setState(prev => ...)) to access current state values inside the listener.