Click twice, and two timers add one each. Why does the count only reach 1? Each timer remembers the count from its own render.
React · intermediate · 8 min · 14 steps · free
import { useState } from 'react';
export default function DelayedCounter() {
const [count, setCount] = useState(0);
function addLater() {
setTimeout(() => {
setCount(count + 1);
}, 1000);
}
return (
<div>
<p>Count: {count}</p>
<button onClick={addLater}>+1 in a second</button>
</div>
);
}<DelayedCounter> for the first time: it calls the DelayedCounter function.useState runs for the first time, so React stores the starting value for count and returns it: 0.DelayedCounter returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.onClick handler.count from this render: 0.setTimeout(() => { setCount(count + 1); }, 1000);.setCount(count + 1) with count = 0 from render 1, so it queues "set to 1".<DelayedCounter> again (render 2): it calls DelayedCounter once more, from the top.useState returns the value React has kept for count: 1. The starting value is only used on the first render.DelayedCounter returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.Answer: Render 1's count
Answer: setCount(c => c + 1)
← Batching: Many Updates, One Render · Keys and Component Identity →