A cart shows item count and total price. Adding an item should increment count by 1 and add 10 to the total in the same click. The total always shows 10 less than expected.
Click Add Item — Count shows 1, Total shows 0. Click again — Count shows 2, Total shows 10. Total is always one step behind.
Both setCount and setTotal run in the same click — what value of count does setTotal actually see?
Both setCount and setTotal run in the same click — what value of count does setTotal actually see?
Why this fixes it
Both setCount(count + 1) and setTotal(total + count * 10) read from the same pre-batch snapshot — inside a single event handler React does not flush state between calls, so count was still 0 when setTotal ran, making the total always one increment behind. Replacing both calls with functional updaters — setCount(c => c + 1) and setTotal(t => t + 10) — removes the dependency on the snapshot entirely. React processes functional updaters sequentially against the latest queued state, so each call operates on the result of the previous one rather than the stale captured value.