Learning on Web Dev Open is free for all.

Framework Internals > State, by where it livesDerived state is not state
Phase 04State, by where it lives199 of 434

Derived state is not state

If you can compute it, computing it is free correctness. Storing it is a second source of truth you now have to keep honest.

Concept13 minAI adversary

A filtered list, a total, a validity flag, whether the button should be disabled: all functions of state you already have. Compute them in the render body. There is no synchronisation to get wrong, no effect to forget, no moment where the list has updated and the count has not.

The effect-that-sets-state pattern is the worst version of this. Watching one value and setting another in an effect gives you an extra render, a frame where the two disagree, and a dependency array that will drift. If you are writing an effect whose only job is to call a setter, you have found a derivation.

Memoisation is a performance tool, not a correctness one, and it has a cost: the comparison, the retained reference, the noise. Reach for it when the computation is genuinely expensive over a genuinely large input, or when the value is a dependency of something that cares about referential identity. Do not reach for it because the value is in a list.

You should now be able to

  • Replace a stored derivation with a computed value
  • Decide honestly whether a memo is warranted
Ask the community

Loading…