Skip to content

The useContext Hook

Context API for sharing data across the component tree without prop drilling.

What you'll learn

  • The problem of prop drilling and how context solves it
  • Creating, providing, and consuming context
  • When to use context vs when to use a state library
  • Performance considerations with context

Concept

The Prop Drilling Problem

When data needs to be accessible by many components at different nesting levels, passing props through every intermediate component is tedious and fragile. This is called prop drilling (or threading). If a deeply nested component needs the current user, you must pass user through every component in between, even if those intermediate components do not use it. This makes refactoring painful and the code harder to follow.

The Context API

React Context solves prop drilling by letting you share data across the entire component tree without passing props manually at every level. You create a context with createContext(defaultValue), provide it high in the tree with <Context.Provider value={...}>, and consume it anywhere below with useContext(Context). The provider creates a scope, and every consumer inside that scope gets the current value.

Creating and Using Context

The typical pattern is to create the context in a separate file, export a custom hook (like useTheme or useAuth) that calls useContext and throws if used outside a provider, and export the provider component. This encapsulates the context and gives a clean API. The provider manages the state and passes both the state and the functions to update it as the context value.

When Not to Use Context

Context is great for low-frequency updates like theme, locale, current user, or authentication status. It is not a replacement for a full state management library. Every consumer of a context re-renders when the context value changes, even if the specific piece they use did not change. For high-frequency updates or complex state logic, consider useReducer with context, or a dedicated state library like Zustand or Redux.

Splitting Contexts

A common optimization is to split a large context into multiple smaller ones. Instead of one AppContext that holds theme, user, and notifications (causing all consumers to re-render on any change), create separate ThemeContext, UserContext, and NotificationContext. Each consumer only re-renders when its specific context changes. This granularity keeps re-renders minimal.

Example

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

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

// 2. Custom hook for consuming the context.
function useTheme() {
  const ctx = useContext(ThemeContext);
  if (!ctx) throw new Error("useTheme must be used within ThemeProvider");
  return ctx;
}

// 3. Provider component that manages state.
function ThemeProvider({ children }) {
  const [theme, setTheme] = useState("light");
  const toggle = () => setTheme(t => t === "light" ? "dark" : "light");
  return (
    <ThemeContext.Provider value={{ theme, toggle }}>
      {children}
    </ThemeContext.Provider>
  );
}

// 4. Consumer — no prop drilling needed.
function Header() {
  const { theme, toggle } = useTheme();
  return (
    <header className={theme}>
      <button onClick={toggle}>Switch to {theme === "light" ? "dark" : "light"}</button>
    </header>
  );
}
            

ThemeContext is created, provided by ThemeProvider, and consumed by Header via the useTheme hook. No props are passed through intermediate components.

Try it

  • JSON Formatter

    Context values are often objects — format them to inspect the shape.

  • Code Diff

    Compare context provider implementations when refactoring.

Common mistakes

The mistake

Using context for high-frequency state updates

The fix

Every context consumer re-renders when the value changes. For frequent updates, split contexts by concern, use useReducer, or choose a state library like Zustand that supports selective subscriptions.

The mistake

Creating a new object as the context value on every render

The fix

If the provider creates a new object value={{ a, b }} on every render, all consumers re-render every time. Memoize the value with useMemo or split into multiple providers.

Practice The useContext Hook

9 exercises

Practice The useContext Hook

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Build real projects

Apply what you learned by building guided projects with starter code and solutions.

View projects

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors