Dynamic Context Slicing and Module Separation
Dynamic Context Slicing and Module Separation
1. The Monolithic Context Trap
In mid-to-large React applications, developers often start with a single AppContext or GlobalContext. Over time, this monolithic context accumulates:
- User profile data
- Theme preferences
- Shopping cart items
- Active navigation tabs
- Toast notifications
- Form drafts
Because of React Context's fundamental update model, whenever ANY value in a Context Provider changes, EVERY component subscribed to that Context re-renders, even if that component only cares about a completely unrelated property!
2. The Solution: Domain-Driven Context Slicing
The enterprise architecture solution decomposes the monolithic context into Domain-Driven Slices:
AuthContext: Manages credentials, tokens, and active user profile.ThemeContext: Manages dark/light modes and visual design tokens.NotificationContext: Manages transient alert banners and toasts.CartContext: Manages e-commerce cart items and checkout calculations.
Each domain slice lives in its own dedicated module, exposing its own typed Provider and custom hook.
3. Dynamic Context Inversion (Colocation)
Not all Contexts need to be global at the application root (src/main.jsx).
The principle of State Colocation dictates:
For example, an <EnrollmentWizard> with 5 steps should have an EnrollmentWizardContext.Provider wrapping only the wizard component, not the entire application! When the wizard unmounts, its context state is cleaned up from memory automatically.
Practice Quiz
GlobalContext an architectural anti-pattern?ThemeContext and Component B consumes AuthContext, what happens when the theme toggles?Context with Bitwise and Proxy Optimizations
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Event-Driven State and Finite State Machines with XState | Context with Bitwise and Proxy Optimizations |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.