Context API & Global State

⚛️ ReactLesson 10Intermediate

Context solves prop drilling — passing data through many layers of components. It creates a global store accessible by any component in the tree without passing props manually at every level.

1 Creating & Using Context
React — Context API
import { createContext, useContext, useState } from "react";

// 1. Create context
const ThemeContext = createContext(null);

// 2. Create provider component
function ThemeProvider({ children }) {
  const [theme, setTheme] = useState("dark");
  const toggle = () => setTheme(t => t === "dark" ? "light" : "dark");

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

// 3. Custom hook for clean consumption
function useTheme() {
  const ctx = useContext(ThemeContext);
  if (!ctx) throw new Error("useTheme must be inside ThemeProvider");
  return ctx;
}

// 4. Consume anywhere in the tree
function Navbar() {
  const { theme, toggle } = useTheme();
  return (
    <nav className={theme}>
      <button onClick={toggle}>Toggle {theme === "dark" ? "☀️" : "🌙"}</button>
    </nav>
  );
}

// 5. Wrap app with provider
function App() {
  return (
    <ThemeProvider>
      <Navbar />
      <MainContent />
    </ThemeProvider>
  );
}
2 Code Challenge
Challenge: Build an AuthContext that holds user (null when logged out) and login / logout functions. Render a LoginPage when user is null, and a Dashboard when logged in — without passing props through intermediate components.