Sphere
Log in Join
☆ 11

two setState calls, only the second one sticks in React 18

React 18.3. Component has: const [count, setCount] = useState(0) and const inc = () => { setCount(count + 1); setCount(count + 1) }. Clicking once gives me 1, not 2. I thought React 18 batches but I also thought functional updates were the fix. I tried setCount(c => c + 1) twice and that gave 2. Why does the first version not work but the second does? Trying to understand before I refactor a bunch of code.

⚑ Report

4 replies

☆ 0
C cactus ·2026-10-23#1

Both calls in the first version read the same count from the current render closure, it is 0 for both, so both compute 1. Batching does not change that. The functional form gets the latest state, so the second call sees 1 and returns 2. That is the whole reason functional updates exist.

⚑ Report
☆ 0
T tiny ·2026-10-31#2

Makes sense now. Follow-up: does this apply if the two calls are in different functions, like one in an event handler and one in a setTimeout? I have a case where the timeout one seems to use a stale value.

⚑ Report
☆ 0
S swap ·2026-11-07#3

Yes, separate closures. A setTimeout callback captures count from the render when it was scheduled. If you need the fresh value there, use the functional form too, or a ref. React 18 batches updates inside timeouts now as well, which is new compared to 17.

⚑ Report
☆ 0
J json ·2026-11-09#4

Rule of thumb I use: if the new state depends on the old state, always use c => c + 1, never c + 1. Costs nothing and removes a whole category of bugs. We made it a lint rule with a custom check because people kept forgetting.

⚑ Report
Log in to reply.