Derive totals during render
Store the inputs, calculate the result
A derived value is determined by other values. If a cart total is completely determined by the current items, calculate it in the component body rather than storing another state variable. This makes the items the canonical source of truth.
import { useState } from 'react';
function totalCents(items) { return items.reduce((sum, item) => sum + item.unitCents * item.quantity, 0);}
export default function App() { const [items, setItems] = useState([ { id: 'mug', name: 'Mug', unitCents: 450, quantity: 2 }, { id: 'tray', name: 'Tray', unitCents: 800, quantity: 1 } ]); const total = totalCents(items); return <main><h1>Cart totals</h1><ul>{items.map(item => <li key={item.id}>{item.name}: {item.quantity}{' '} <button type="button" onClick={() => setItems(old => old.filter(x => x.id !== item.id))}> Remove {item.name} </button></li>)}</ul> <p role="status">Total: USD {(total / 100).toFixed(2)}</p> </main>;}The initial total is USD 17.00 (900 + 800 cents). Remove the mug to see USD 8.00, then remove the tray to see USD 0.00. reduce starts its running sum at zero, including for an empty list. Integer cents avoid fractional-dollar arithmetic in this small fixture; inputs are nonnegative safe integers and totals fit within the safe integer range. Real billing must validate prices and totals on the server.
Derive counts and messages from the same data
import { useState } from 'react';
export default function App() { const [items, setItems] = useState([{ id: 'mug', quantity: 2 }, { id: 'tray', quantity: 0 }]); const units = items.reduce((sum, item) => sum + item.quantity, 0); return <main><h1>Cart summary</h1> <p>Product rows: {items.length}</p><p>Units: {units}</p> <p>{units === 0 ? 'No units selected' : 'Ready to review'}</p> <button type="button" onClick={() => setItems(old => old.map(item => ({ ...item, quantity: 0 })))}>Clear quantities</button> <button type="button" onClick={() => setItems([])}>Remove all rows</button> </main>;}Initially there are two rows and two units. Clear quantities leaves two rows but zero units. Remove all rows leaves zero rows and zero units. These are different meanings of empty; name the condition you intend. Each value is recomputed from the same current array, avoiding conflicting stored flags.
Avoid duplicated totals
import { useState } from 'react';
export default function App() { const [items, setItems] = useState([{ id: 'mug', unitCents: 450, quantity: 2 }]); const [total] = useState(900); return <main><h1>Cart</h1><p>Rows: {items.length}</p><p>Total cents: {total}</p> <button type="button" onClick={() => setItems([])}>Empty cart</button> </main>;}After Empty cart, the row count is zero but the stored total remains 900. Do not repair this by adding another setter to every possible cart action or by synchronizing the total with an Effect (a later topic). Derive it from items as in the first example. Keep independently editable information, such as a delivery choice, in state when it cannot be computed from the cart. For costly calculations measure before considering caching; these tiny reductions need no extra mechanism.
Practice
Add a subtotal and a fixed 200-cent delivery fee, charged only when the total selected unit count is positive. Derive the payable total; test empty, zero-quantity and normal carts.