← Lessons

quiz vs the machine

Gold1380

Frontend

The Derived State and Selectors

Compute values from source state instead of storing them, and use memoized selectors to keep it cheap.

5 min read · core · beat Gold to climb

Do not store what you can compute

Derived state is any value you can calculate from existing state, like a filtered list, a total, or a flag. Storing it separately invites bugs because the copy can fall out of sync with its source. The rule is to compute it during render instead.

  • A total derived from items is always correct because it recomputes.
  • A stored total can drift when items change but the total is not updated.
  • Fewer stored fields means fewer chances for inconsistency.

Selectors and memoization

A selector is a small function that reads source state and returns a derived value. Wrapping it in memoization avoids recomputing when inputs have not changed.

  • A memoized selector caches its result keyed by its inputs.
  • It recomputes only when an input reference changes.
  • This keeps expensive derivations from running on every render.

When derivation gets expensive

If a derivation is heavy, memoize it; if it depends only on props and state, compute it inline. Reach for stored state only when you must capture a value at a moment, like a snapshot, not when it can be recomputed.

Key idea

Compute derived values from source state rather than storing them, and use memoized selectors so expensive derivations only rerun when their inputs change.

Check yourself

Answer to earn rating on the learn ladder.

1. Why prefer deriving a total over storing it?

2. What does memoizing a selector accomplish?