Member-only story
Your React Cart Doesn’t Need a Total in State
Ferid Brković
4 min read3 hours ago
Press enter or click to view image in full size
Remove a synchronization step by calculating the current total from the current inputs.
A cart has two items at $12 each and one at $6. Its total is $30. Apply a 10% discount, and the displayed total should become $27.
There are two ways to model that screen. Store the items and discount, then calculate the total. Or store all three and write code to keep them in agreement.
The second version can look more “React-like” because it uses another Hook. It also creates another obligation: every change to the cart must eventually reach that extra state variable.
That obligation is optional. The interesting fix is deciding which values deserve their own memory.
The receipt is an answer, not another input
For this example, prices are integer cents, quantities are nonnegative integers, and the discount is either zero or ten percent.…