Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Routing and Application Architecture
Stage 5: Specialization (pick ONE)

Part 09 / Topic 2 of 6

createContext, Provider, and useContext

examples/02_create_context_provider_consumer.jsx rebuilds the exact same toggle with context instead:

// examples/02_create_context_provider_consumer.jsx
const ThemeContext = createContext(null);

export function ThemedAppWithContext() {
  const [theme, setTheme] = useState("light");
  function toggleTheme() { setTheme((c) => (c === "light" ? "dark" : "light")); }

  return (
    <ThemeContext.Provider value={{ theme, toggleTheme }}>
      <LayoutWithContext />
    </ThemeContext.Provider>
  );
}

function ThemeBadgeWithContext() {
  const { theme, toggleTheme } = useContext(ThemeContext);
  // ...
}

createContext(null) creates one context object, shared by reference by every file that imports it. <ThemeContext.Provider value={...}> makes that value available to every component rendered anywhere inside it, at any depth. useContext(ThemeContext) reads the nearest matching Provider's current value - here, straight from ThemeBadgeWithContext, three levels down, with no theme or toggleTheme anywhere in LayoutWithContext's or SidebarWithContext's signatures at all. The same toggle click really flips the same "Theme: light"/"Theme: dark" text (examples/02_create_context_provider_consumer.test.jsx) - identical behavior, with the pass-through plumbing gone.

Done here? The practice set for Part 9 — including the solutions — is on the part page.

Search the guide