Example: Calculating Totals and Aggregates
What you'll learn: How to derive sums, averages, counts, and other aggregate calculations from your state without needing useEffect.
When you have an array of items in state—like a shopping cart, a list of expenses, or user scores—you often need to display totals, averages, or counts. A common mistake is calculating these values in a useEffect and storing them in separate state variables. This creates unnecessary complexity and double renders.
The Wrong Way (Using useEffect)
const [items, setItems] = useState([
{ name: 'Apple', price: 1.50, qty: 3 },
{ name: 'Bread', price: 2.00, qty: 1 }
]);
const [total, setTotal] = useState(0);
useEffect(() => {
const sum = items.reduce((acc, item) =>
acc + (item.price * item.qty), 0
);
setTotal(sum);
}, [items]);
This works, but it's wasteful: React renders once with a stale total, then the effect runs and triggers another render with the updated value.
The Right Way (Direct Calculation)
const [items, setItems] = useState([
{ name: 'Apple', price: 1.50, qty: 3 },
{ name: 'Bread', price: 2.00, qty: 1 }
]);
// Calculate during render
const total = items.reduce((acc, item) =>
acc + (item.price * item.qty), 0
);
const itemCount = items.length;
const average = total / itemCount;
Now total, itemCount, and average are always in sync with items—no effect needed, no double render.
Why This Works
Aggregates like sums and counts are derived data—they're completely determined by existing state. Computing them during render is fast (JavaScript handles these operations in microseconds) and guarantees consistency.
Key Takeaway: Calculate totals, averages, counts, and other aggregates directly during render—they derive from existing state and don't require synchronization or effects.