Creating Separate Contexts by Concern
What you'll learn: How to split a monolithic context into multiple focused contexts to improve performance and maintainability.
The Problem with One Big Context
When you stuff all global state into a single context—theme settings, user data, app preferences, notifications—every component that reads any part of that context re-renders whenever anything changes. A theme toggle causes every component to re-render, even those that only care about the user's name.
The Solution: Split by Concern
Instead of one giant context, create separate contexts for logically independent concerns:
// ❌ Before: Monolithic AppContext
const AppContext = createContext({
theme: 'light',
user: null,
settings: {},
// ... everything bundled together
});
// ✅ After: Separate contexts
const ThemeContext = createContext('light');
const UserContext = createContext(null);
const SettingsContext = createContext({});
Independent Providers
Each context gets its own provider, typically stacked in your app root:
function App() {
return (
<ThemeProvider>
<UserProvider>
<SettingsProvider>
<YourApp />
</SettingsProvider>
</UserProvider>
</ThemeProvider>
);
}
The Performance Win
Now components subscribe only to what they need. A component that reads useContext(ThemeContext) won't re-render when user data changes. A component reading useContext(UserContext) ignores theme updates. Each context maintains its own subscription list.
The Analogy
Think of it like magazine subscriptions. Instead of forcing everyone to subscribe to a bundle (news + sports + fashion), let people subscribe to individual magazines. You only get deliveries when your subscription has new content.
Key Takeaway: Split large contexts into smaller, focused contexts by concern (theme, user, settings) so components only re-render when their specific data changes, not when unrelated state updates.