R
Rishtaara
React: The Complete Guide
Lesson 18 of 28Article16 min

useContext Hook

createContext makes a context. Provider wraps part of your tree and passes a value. useContext reads that value in any child — no passing props through every level.

useContext — share data without prop drilling

createContext makes a context. Provider wraps part of your tree and passes a value. useContext reads that value in any child — no passing props through every level.

Real-life example: Context is Wi-Fi in a building. You connect once at the router (Provider); every room (component) gets signal without running cables through each door (props).

Theme context
import { createContext, useContext, useState } from "react";

const ThemeContext = createContext("light");

export function ThemeProvider({ children }) {
  const [theme, setTheme] = useState("light");
  return (
    <ThemeContext.Provider value={{ theme, setTheme }}>
      {children}
    </ThemeContext.Provider>
  );
}

export function useTheme() {
  return useContext(ThemeContext);
}

function Toggle() {
  const { theme, setTheme } = useTheme();
  return (
    <button onClick={() => setTheme(theme === "light" ? "dark" : "light")}>
      {theme === "light" ? "Dark mode" : "Light mode"}
    </button>
  );
}

When to use Context

Good for theme, auth user, locale — data many components need but that changes rarely.

For fast-changing or complex state, consider Zustand or Redux instead of one giant context.

Real-life example: Context is the school notice board — everyone reads it; you do not pass the same announcement through every classroom door.

  • Split contexts — AuthContext, ThemeContext — not one mega context
  • Memoize provider value when it is an object to avoid extra re-renders
  • Custom hooks (useAuth) hide context details from UI components