Course contentsShow
← React
Lesson 1624 of 2,39639. Server Components in PracticeFree lesson

When You MUST Use Client: Context Providers

Context providers and consumers (useContext) must be Client Components since context relies on React's client runtime.

When You MUST Use Client: Context Providers

What you'll learn: Why React Context providers and consumers must always be Client Components, not Server Components.

The Core Constraint

Context in React relies on the client-side runtime to manage state across component trees. Because of this fundamental dependency, both Context providers and any components using useContext must be Client Components. Server Components cannot create or consume context.

Think of context like a shared memory space that components check and update during render. Server Components render once on the server and send static output — they don't have access to this persistent, client-side memory system. They're stateless snapshots, while context requires ongoing state management.

The Pattern in Practice

'use client'; // REQUIRED at the top of this file

import { createContext, useContext } from 'react';

const ThemeContext = createContext('light');

// This provider MUST be a Client Component
export function ThemeProvider({ children }) {
  const [theme, setTheme] = useState('light');
  
  return (
    <ThemeContext.Provider value={{ theme, setTheme }}>
      {children}
    </ThemeContext.Provider>
  );
}

// Consumers also need 'use client'
export function ThemedButton() {
  const { theme } = useContext(ThemeContext);
  return <button className={theme}>Click me</button>;
}

The provider needs useState and manages client state. Any component calling useContext needs the client runtime to access that shared state. Both requirements force the 'use client' boundary.

Strategy: Wrap High, Keep Server Components as Children

Place your provider as high as needed, but pass Server Components as children. The provider is client-side, but its children can still be server-rendered.

Key Takeaway: Context providers and useContext consumers must be Client Components because context depends on React's client-side runtime for state management — Server Components can't participate in this system.