Skip to content

QuizNot attempted

setState inside setTimeout (React 18)

Click once and wait. What does the button eventually show, and are the two setCount calls inside setTimeout batched into one re-render (React 18)?
function App() {
const [count, setCount] = useState(0);
function handleClick() {
setTimeout(() => {
setCount(count + 1);
setCount(count + 1);
}, 0);
}
return <button onClick={handleClick}>{count}</button>;
}
1–4 to choose, Enter to submit
Show answer & explanation

Correct answer:

  • 1, batched into one render
  • React 18 batches updates everywhere (timeouts, promises, native handlers), so the two calls produce one render, and both read the same stale count (0) from the click's render, so the result is 1.
  • Not 2: neither call is a functional update.
  • Not 'two separate renders': that was React 17 behaviour outside React event handlers.