puzzle 07 · javascript

After clicking once, what is count?

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

function onClick() {
  setCount(count + 1);
  setCount(count + 1);
}
2
1
0
It depends on batching

why

Both calls read the same `count` from the render's closure, so both compute 0 + 1. The second overwrites the first. Use the updater form — setCount(c => c + 1) — to queue on the latest value and get 2.

Today's puzzlea new one every day, and a streak to keep