Skip to content

QuizNot attempted

Event listener reading stale state

Click the button 3 times (value becomes 3), then trigger a resize event. What does the console log show for 'current value:'?
function App() {
const [value, setValue] = useState(0);
useEffect(() => {
function handleResize() {
console.log('current value:', value);
}
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return <button onClick={() => setValue(v => v + 1)}>{value}</button>;
}
1–4 to choose, Enter to submit
Show answer & explanation

Correct answer:

  • 0
  • With [] the effect ran once, so handleResize is the function created in the mount render and its value is frozen at 0
  • the listener is still attached, it just reads stale state.
  • Not 3: the listener never sees later renders.
  • Not 'listener removed': cleanup only runs on unmount.
  • Not 1: there is no render where the closure captured 1.
  • Fix: add value to deps, read from a ref, or use useEffectEvent.