Course contentsShow
← React
Lesson 1697 of 2,39641. State Management EcosystemFree lesson

Patterns That Keep Context Viable

Use memoization, split contexts, and colocate state to keep Context performant at scale.

Patterns That Keep Context Viable

What you'll learn: How to prevent Context from becoming a performance bottleneck as your app scales.

Context is powerful, but it has a key weakness: every consumer re-renders when the context value changes. As your app grows, this can become expensive. The good news? Three patterns keep Context performant even in larger applications.

The Core Problem

When a context value updates, every component using that context re-renders, even if it only cares about one small piece of the data. This creates a performance cliff as your component tree grows.

Pattern 1: Split Contexts

Instead of one giant context, create multiple smaller ones:

// ❌ Everything re-renders when anything changes
const AppContext = createContext({ user, theme, settings, notifications });

// ✅ Only affected consumers re-render
const UserContext = createContext(user);
const ThemeContext = createContext(theme);

Analogy: Instead of one bulletin board where everyone checks for everything, use separate boards for HR, IT, and Sales.

Pattern 2: Memoize the Context Value

Prevent unnecessary updates by stabilizing the value object:

const value = useMemo(() => ({ user, theme }), [user, theme]);
return <AppContext.Provider value={value}>...

Without memoization, a new object is created every render, triggering all consumers.

Pattern 3: Colocate State

Keep state as local as possible. Only lift to context when truly needed across distant components. The closer state lives to where it's used, the fewer components re-render when it changes.

When to Apply These

Use these patterns when you notice:

  • Components re-rendering unnecessarily
  • Context holding multiple unrelated pieces of state
  • Performance degradation as your app grows

Key Takeaway: Context stays viable at scale when you split it into focused pieces, memoize provider values, and keep state local by default—only lifting what's genuinely shared.