Colocation: Keep State Close to Where It's Used
What you'll learn: Why state should live in the component that uses it, not hoisted up to global stores or distant parents.
The Core Principle
Colocation means placing state as close as possible to where it's actually used. If a piece of state only affects one component and its children, it should live in that component—not in a global store, not in a distant parent, not in context.
Why This Matters
Think of state like kitchen supplies. You keep your coffee filters near the coffee maker, not in the garage. Why? Because that's where you use them. The same logic applies to React state.
When state lives far from where it's used:
- Code is harder to understand (you have to hunt for where state is defined)
- Components become harder to move or reuse (they depend on distant parents or global stores)
- Performance suffers (changes trigger unnecessary re-renders in unrelated parts of the tree)
- Testing gets complicated (you need to mock global stores or wrap components in providers)
The Rule of Thumb
Ask yourself: "What's the smallest subtree that needs this state?" That's where it should live.
A modal's open/closed state? In the modal component, not in Redux.
A form's input values? In the form component, not in a parent page.
User authentication status? That's truly global—context or a store makes sense.
Example Pattern
If only <SearchBar> needs searchTerm, put useState inside <SearchBar>. Don't lift it to the page component "just in case." You can always lift it later if requirements change.
Key Takeaway: State that affects only one component or its direct children belongs in that component. Resist the urge to hoist prematurely—locality makes code easier to understand, test, and maintain.