Course outline · 0% complete

0/28 lessons0%

Course overview →

Derived state: compute, don't store

lesson 8-2 · ~11 min · 23/28

Derived state: compute, don't store

A common beginner instinct is to create state for everything on screen. But if a value can be computed from existing state or props, it should not be state at all, just compute it during render:

function Cart({ items }) {
  // NOT state, plain consts computed on every render
  const subtotal = items.reduce((sum, it) => sum + it.price * it.qty, 0);
  const shipping = subtotal >= 100 ? 0 : 7;
  return <p>Total: {subtotal + shipping}</p>;
}

reduce is the array-folding tool from Advanced JavaScript. Every render recomputes these consts from the freshest items, so they can never be out of date.

Storing them in state instead would mean updating TWO things on every cart change, and forgetting is the sync bug from lesson 1-1 all over again, this time inside React. The rule of thumb: state is only for facts React cannot compute, everything else is derived.

Code exercise · javascript

Derived values as pure functions. subtotal folds price × qty over the items, shipping derives from subtotal, total derives from both. Run it, then change Cable's qty to 30 and run again to see every derived value stay consistent automatically (set it back before checking).

Code exercise · javascript

Your turn. Write remaining(tasks), the count of tasks where done is false, and summary(tasks), which returns "All done!" when nothing remains, otherwise "N task(s) left". These are exactly the derived values a task tracker renders.

Quiz

Spot the design bug: ```jsx const [tasks, setTasks] = useState([]); const [taskCount, setTaskCount] = useState(0); function addTask(t) { setTasks([...tasks, t]); setTaskCount(taskCount + 1); } ```