Course contentsShow
← React
Lesson 684 of 2,39618. When NOT to Use useEffectFree lesson

Derived State: Compute During Render Instead

How to calculate values directly from props in the render phase, eliminating unnecessary effects and state.

Derived State: Compute During Render Instead

What you'll learn: How to eliminate unnecessary effects and state by calculating values directly from props during render.

The Core Idea

When you need a value that's based entirely on props or other state, don't store it in state and don't calculate it in an effect. Just compute it directly in your component body during render. React's rendering is fast enough to handle these calculations, and you'll avoid synchronization bugs.

Why This Matters

Beginners often reach for useEffect to "watch" props and update derived state. This creates two problems:

  1. Extra render cycles — the component renders once with stale derived data, then the effect runs and triggers a second render
  2. Synchronization bugs — the derived state can fall out of sync with its source

The Right Pattern

function ProductCard({ price, quantity }) {
  // ❌ Wrong: using effect to derive state
  // const [total, setTotal] = useState(0);
  // useEffect(() => {
  //   setTotal(price * quantity);
  // }, [price, quantity]);

  // ✅ Right: compute during render
  const total = price * quantity;

  return <div>Total: ${total}</div>;
}

The value total is derived from price and quantity. There's no need for state or effects — just calculate it directly. Every time props change, the component re-renders anyway, and total gets recalculated automatically.

When to Use This

Use direct computation whenever a value can be calculated from:

  • Props alone
  • Existing state alone
  • A combination of props and state

The calculation happens during render, stays in sync automatically, and avoids unnecessary complexity.

Key Takeaway: If you can calculate a value from props or state, compute it during render — don't store it in state or update it in an effect.