Derived State: Compute, Don't Store
What you'll learn: How to avoid redundant state by calculating values during render instead of storing them separately.
The Core Idea
If you can calculate a value from existing state or props during render, don't create a separate useState for it. Compute it on-the-fly instead. This eliminates synchronization bugs and simplifies your component logic.
Think of it like a spreadsheet: you don't store the sum in a separate cell and manually update it whenever numbers change. You write a formula that calculates the sum automatically. React components work the same way.
Why This Matters
When you store derived data in separate state:
- You must remember to update it whenever the source data changes
- You risk the derived state getting out of sync
- You add unnecessary complexity and re-renders
The Pattern
❌ Don't do this:
const [items, setItems] = useState([]);
const [itemCount, setItemCount] = useState(0); // Derived!
// Now you must update itemCount every time items changes
✅ Do this instead:
const [items, setItems] = useState([]);
const itemCount = items.length; // Computed during render
The computed version is always correct, requires no synchronization, and is just as fast (React re-renders are already happening).
Common Examples
- Total price from cart items
- Filtered or sorted lists from a source array
- Validation status from form field values
- Character counts from text input
Key Takeaway: If you can derive a value from existing state with simple JavaScript during render, compute it—don't store it in useState.