← Lessons

quiz vs the machine

Gold1440

Frontend

Derived State and Selectors

Compute values from source state instead of storing them, using memoized selectors.

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. Storing it too creates two sources of truth that drift out of sync.

  • A filtered list derives from the full list plus a filter.
  • A total derives from line items.
  • An is valid flag derives from the form fields.

Keep the minimal source state and compute the rest on read.

Selectors

A selector is a function that reads source state and returns a derived value. Centralizing this logic keeps components thin.

  • Components subscribe to a selector rather than reaching into raw state.
  • The derivation lives in one place, easy to test.
  • Changing the shape of state only updates the selector.

Memoization

Recomputing a heavy derivation on every render wastes work. A memoized selector caches its last inputs and output, returning the cached result when inputs are unchanged. This relies on stable references, which is why immutable updates pair well with selectors.

Key idea

Store only source state and expose derived values through memoized selectors so there is one source of truth and no wasted recomputation.

Check yourself

Answer to earn rating on the learn ladder.

1. Why avoid storing derived values in state?

2. What does a memoized selector return when its inputs are unchanged?

3. Why do memoized selectors rely on stable references?