Splitting Context in Existing Codebases
What you'll learn: How to safely refactor a monolithic Context into smaller, performance-optimized Contexts without breaking your app.
The Real-World Challenge
You've identified that a single Context is causing performance issues (see lesson 838). But you have a working codebase with dozens of components reading from it. How do you split it without introducing bugs or downtime?
The Refactoring Strategy
1. Identify Hot Paths
Use React DevTools Profiler to find components that re-render frequently but consume only a small slice of your Context. These are your hot paths — the performance bottlenecks where splitting will have the biggest impact.
2. Split Incrementally
Don't refactor everything at once. Extract one independent state domain (lesson 839) at a time:
- Create the new Context
- Build a new Provider alongside the old one
- Gradually migrate consumers component-by-component
- Keep the old Context running until all consumers have moved
This allows you to test each change in isolation and roll back if needed.
3. Validate with Tests
Before and after each split:
- Run your existing component tests
- Add integration tests that verify the new Context works
- Check that unchanged components still behave correctly
Think of it like replacing planks on a bridge while people are walking across — you do it one plank at a time and verify each one holds weight before moving on.
Example Migration Order
- Profile → find
<ExpensiveList>re-renders from theme changes - Create
ThemeContextseparate fromAppContext - Migrate
<ExpensiveList>to read onlyThemeContext - Test, measure improvement
- Repeat for other theme consumers
Key Takeaway: Refactor Context splits incrementally by profiling hot paths first, extracting one domain at a time, and validating each step with tests to avoid breaking existing functionality.