Computing Derived Values Directly in Render
What you'll learn: How to calculate values based on props or state without unnecessary effects or extra state variables.
The Core Idea
When you need a value that's based on existing props or state, just calculate it during render. You don't need useEffect to "sync" it, and you don't need a separate state variable to store it. React components re-render when their inputs change, so the derived value will automatically stay up-to-date.
Think of it like a spreadsheet: when cell A1 changes, the formula in B1 (=A1*2) doesn't need a special "sync" step—it just recalculates automatically. Your React component works the same way.
How It Looks
Instead of this broken pattern:
const [items, setItems] = useState([]);
const [itemCount, setItemCount] = useState(0);
useEffect(() => {
setItemCount(items.length); // ❌ Unnecessary effect
}, [items]);
Do this:
const [items, setItems] = useState([]);
const itemCount = items.length; // ✅ Direct calculation
The itemCount variable recalculates every render. Since items is already in scope, the derived value is always correct—no effect needed.
Why This Works
Every time items changes, React re-renders your component. During that render, itemCount is recalculated with the new value. There's no "lag" and no extra render cycle from setting state in an effect.
This pattern works for filtering, mapping, sorting, formatting—any pure calculation based on props or state.
When to Use useMemo Instead
If the calculation is genuinely expensive (processing thousands of items, complex computations), wrap it in useMemo to avoid recalculating on every render. But start simple—compute directly first.
Key Takeaway: Derived values should be computed during render as regular variables, not stored in state or synced with effects—React's natural re-rendering keeps them fresh automatically.