Course contentsShow
← React
Lesson 2323 of 2,39650. Performance: Optimization TechniquesFree lesson

Split Contexts by Concern

Breaking monolithic context into multiple focused contexts so components only subscribe to the data they actually use.

Split Contexts by Concern

What you'll learn: How to break apart a monolithic context into multiple focused contexts so components only re-render when the specific data they care about changes.

The Problem with One Big Context

When you pack user data, theme settings, notifications, and auth status all into a single context, every consumer re-renders whenever any piece of that context updates. A component that only reads the current username gets forced to re-render when the theme changes.

Split by What Changes Together

The solution: create separate contexts for distinct concerns. A UserContext for profile data, a ThemeContext for appearance, a NotificationContext for alerts. Now components subscribe only to what they actually use.

// ❌ Before: One monolithic context
const AppContext = createContext();

function AppProvider({ children }) {
  const [user, setUser] = useState(null);
  const [theme, setTheme] = useState('light');
  const [notifications, setNotifications] = useState([]);
  
  // ANY change here rerenders ALL consumers
  return (
    <AppContext.Provider value={{ user, setUser, theme, setTheme, notifications, setNotifications }}>
      {children}
    </AppContext.Provider>
  );
}

// ✅ After: Split by concern
function UserProvider({ children }) {
  const [user, setUser] = useState(null);
  return <UserContext.Provider value={{ user, setUser }}>{children}</UserContext.Provider>;
}

function ThemeProvider({ children }) {
  const [theme, setTheme] = useState('light');
  return <ThemeContext.Provider value={{ theme, setTheme }}>{children}</ThemeContext.Provider>;
}

Now UserProfile only re-renders when user changes. ThemeToggle only re-renders when theme changes. They're isolated from each other's updates.

The Analogy

Think of it like separate notification channels. Instead of one noisy group chat where everyone gets pinged for everything, you have focused channels—#engineering, #design, #sales—where you only get updates about topics you care about.

Key Takeaway: Split context by domain concern so components subscribe only to the data they actually use, preventing unnecessary re-renders across unrelated parts of your app.