Learning on Web Dev Open is free for all.

Framework Internals > State, by where it livesKeep it local until something else needs it
Phase 04State, by where it lives198 of 434

Keep it local until something else needs it

Lift state to the closest common ancestor and no further. The instinct to hoist everything to the top is how a codebase becomes one enormous component.

Concept12 minAI pair

State at the top re-renders everything below it. State at the bottom re-renders one subtree. That is the performance argument and it is real, but the maintainability argument is stronger: state near where it is used can be understood by reading one file, and state at the root can only be understood by searching the whole application for consumers.

The right move is to lift only when a second component genuinely needs the same value, and only as far as their nearest common ancestor. If that ancestor is the root, ask whether the two components should be closer together instead, or whether the value should be in the URL.

Colocation extends past state. Keep the types, the helpers and the small subcomponents next to the thing that uses them, and move them up only on the second consumer. Premature extraction into a shared folder is the same mistake as premature hoisting, and it is harder to reverse because by then three unrelated things import it.

You should now be able to

  • Place state at the lowest level that works
  • Recognise when hoisting has gone too far
Ask the community

Loading…