Training Grounds
Total Price Is Always One Click BehindBlue Belt
+25 Ki
Description

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.

Anomaly

Click Add Item — Count shows 1, Total shows 0. Click again — Count shows 2, Total shows 10. Total is always one step behind.

Constraint
Do not merge them into a single state object
Hint

Both setCount and setTotal run in the same click — what value of count does setTotal actually see?

Consult the SenseiOnly for those truly stuck · Flip to reveal

Both setCount and setTotal run in the same click — what value of count does setTotal actually see?

Loading editor…
Correct Solution
Loading...

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.

Expected OutputGoal State
Your OutputLive