Context

Topic 1 of 3 in Sharing state7 min readIntermediateFree course

Overview

Passing props works well until a value is needed by many components at different depths: the current user, the theme, the language, permissions. Threading it through every layer — even components that don’t use it — is called prop drilling, and it makes components noisy and hard to move. Context lets a parent make a value available to its whole subtree.

With prop drilling, App passes theme=“dark” to Layout, which passes it to Sidebar, which passes it to UserMenu — middle components pass props they don’t use. With context, App renders a ThemeContext provider with the value dark, and UserMenu reads it directly with useContext; any descendant can read it.

Three steps

1. Create the context

JSX
// ThemeContext.js
import { createContext } from 'react';

export const ThemeContext = createContext('light');

The argument is the default value, used only when a component reads the context without any provider above it.

2. Provide a value

Wrap part of your tree with the context and give it a value:

JSX
import { ThemeContext } from './ThemeContext.js';

export default function App() {
  const [theme, setTheme] = useState('dark');

  return (
    <ThemeContext value={theme}>
      <Layout />
      <button onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}>Toggle</button>
    </ThemeContext>
  );
}

In React 19 you render the context itself as the provider. Older code writes <ThemeContext.Provider value={theme}>, which still works.

3. Read it anywhere below

JSX
import { useContext } from 'react';
import { ThemeContext } from './ThemeContext.js';

function UserMenu() {
  const theme = useContext(ThemeContext);
  return <nav className={`menu menu-${theme}`}>…</nav>;
}

Layout and Sidebar no longer need a theme prop at all. UserMenu reads it directly, however deep it is.

How context resolves values

  • A component gets the value from the nearest provider above it in the tree.
  • Providers can be nested to override a value for a subtree:
JSX
<ThemeContext value="dark">
  <Page />
  <ThemeContext value="light">
    <Footer />          {/* sees "light" */}
  </ThemeContext>
</ThemeContext>
  • When a provider’s value changes, every component that reads that context re-renders with the new value — even if components in between skip rendering.

The provider-plus-hook pattern

In real apps, wrap each context in two pieces: a provider component that owns the state, and a custom hook for reading it.

JSX
// auth.jsx
import { createContext, useContext, useState } from 'react';

const AuthContext = createContext(null);

export function AuthProvider({ children }) {
  const [user, setUser] = useState(null);

  async function login(email, password) {
    const res = await fetch('/api/login', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email, password }),
    });
    if (!res.ok) throw new Error('Login failed');
    setUser(await res.json());
  }

  function logout() {
    setUser(null);
  }

  return <AuthContext value={{ user, login, logout }}>{children}</AuthContext>;
}

export function useAuth() {
  const ctx = useContext(AuthContext);
  if (!ctx) throw new Error('useAuth must be used inside <AuthProvider>');
  return ctx;
}
JSX
// main.jsx
<AuthProvider>
  <App />
</AuthProvider>

// anywhere in the app
function Header() {
  const { user, logout } = useAuth();
  return user ? <button onClick={logout}>Log out {user.name}</button> : <a href="/login">Log in</a>;
}

Benefits:

  • components import useAuth, never the raw context — you can change the implementation later,
  • the null default plus the check gives a clear error if someone forgets the provider,
  • all the auth logic lives in one file.

Reading context with use

React 19’s use API can also read context. Unlike useContext, it can be called inside conditions and loops:

JSX
import { use } from 'react';

function Heading({ children }) {
  if (!children) return null;
  const theme = use(ThemeContext);    // fine after an early return
  return <h1 className={theme}>{children}</h1>;
}

useContext remains the common choice; reach for use when you need conditional reads.

Performance considerations

Every component that reads a context re-renders when its value changes. Two things help:

Don’t create a new object on every render unless something changed. value={{ user, login, logout }} creates a new object each time the provider renders. If the provider re-renders for unrelated reasons, all consumers re-render too. Memoise the value — or let React Compiler do it:

JSX
const value = useMemo(() => ({ user, login, logout }), [user]);
return <AuthContext value={value}>{children}</AuthContext>;

(login and logout would also need useCallback for this to fully work; with React Compiler enabled, all of this happens automatically.)

Split contexts by how often they change. A frequently changing value (say, the current mouse position) in the same context as a rarely changing one (the user) makes everything re-render often. Use separate contexts, as the next lesson does with state and dispatch.

When to use context

Good uses Better alternatives
theme, locale, current user, permissions passing a prop one or two levels — just use props
a component library’s internal state (tabs, menus) layout wrappers — pass JSX as children
app-wide state with useReducer (next lesson) server data — use TanStack Query or your router
very frequently changing global state — an external store

Context isn’t a state manager by itself — it’s a transport for values. The state still lives in a component with useState or useReducer.

Try composition first. Before adding context to avoid passing a prop, check whether the in-between components could accept children instead (see Children and composition). Often that removes the drilling entirely.

Exercise

A theme switcher

Create a ThemeContext with a default of 'light'. Write a ThemeProvider({ children }) that holds the theme in state and provides { theme, toggleTheme }. Write a useTheme() hook that reads the context and throws a helpful error if it’s used outside the provider. Use it in a ThemeToggle button (“Switch to dark mode” / “Switch to light mode”) and a Card that adds the class card-dark in dark mode.

JavaScript
import { createContext, useContext, useState } from 'react';

const ThemeContext = createContext(null);

export function ThemeProvider({ children }) {
  // your code here
}

export function useTheme() {
  // your code here
}

Summary

  • Context lets a parent provide data to any component below it, without passing props through every level.
  • createContext(default) creates it; <MyContext value={…}> provides it; useContext(MyContext) reads it.
  • A component reads the value from the nearest provider above it, or the default if there is none.
  • When the provided value changes, every component reading that context re-renders.
  • Wrap context in a provider component and a custom hook; use it for widely needed data, not to avoid passing two props.