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

A cart shows item count and total price, both updating together whenever an item is added.

Anomaly

Click Add Item - Count shows 1, Total shows $0. Click again - Count shows 2, Total shows $10. Total is always one step behind the correct value.

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?

Practice 14 related drills →
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. Replacing both calls with functional updaters removes the dependency on the snapshot entirely. React processes functional updaters sequentially against the latest queued state.

Expected OutputGoal State
Your OutputLive