Chapter 2 · Practice 2 of 5
Keep state as close as possible to where it is used
From State and data flow
Why it matters
State placed too high in the tree makes every component below it re-render on each change, and makes the data flow harder to follow.
- Start with state in the component that uses it.
- Lift it to the nearest common parent only when two siblings need the same value.
- Use context when many distant components need the same value, such as the current user or theme.
Context is not a replacement for all state. A value that changes on every keystroke should not sit in a context that wraps the whole app.
Split contexts by how often they change, so fast-changing values do not re-render consumers of slow-changing ones.
Do
- Lift state up only to the closest shared parent
- Split fast-changing and slow-changing values into separate contexts
Avoid
- A single global context object holding all app state