airair
All questions

Stale closure in a timeout

NewQuizReactmedium~3 minclosures, useState, event handlers
function Counter() {
  const [count, setCount] = useState(0);

  function showLater() {
    setTimeout(() => alert(count), 3000);
  }

  return (
    <>
      <button onClick={() => setCount(count + 1)}>+1</button>
      <button onClick={showLater}>Show in 3s</button>
    </>
  );
}

The user clicks Show in 3s while the count is 0, then clicks +1 twice within the next second. What does the alert display?

Choose one answer