NelsonLabs
React Fundamentals/Context — Sharing State

Context — Sharing State

Context solves the prop drilling problem — when you need to pass data through many layers of components that don't actually use it, just to get it to a deeply nested component.

ANALOGY

Context is a broadcast channel. Props pass data like a telephone chain — each person passes the message to the next. Context broadcasts to everyone who's listening. Any component in the tree can subscribe and receive the data directly, no matter how deep it is.

Context — create, provide, consume
jsx
import { createContext, useContext, useState } from "react";

// 1. Create the context
const ThemeContext = createContext("dark");

// 2. Provide it at the top of your tree
function App() {
  const [theme, setTheme] = useState("dark");

  return (
    <ThemeContext.Provider value={{ theme, setTheme }}>
      <Header />
      <Main />
      <Footer />
    </ThemeContext.Provider>
  );
}

// 3. Consume it anywhere in the tree (no prop passing needed)
function ThemeToggle() {
  const { theme, setTheme } = useContext(ThemeContext);

  return (
    <button onClick={() => setTheme(theme === "dark" ? "light" : "dark")}>
      Switch to {theme === "dark" ? "light" : "dark"} mode
    </button>
  );
}

// ThemeToggle can be anywhere in the tree — doesn't matter
// how deeply nested it is

TIP

Context is not a replacement for all state. Context is for global state: theme, authenticated user, language, cart. Don't put every piece of state in context. Local component state (a dropdown is open, a form field value) stays local. Reach for context when truly multiple distant components need the same data.