Context

Passing data deep without props, and what it costs.

Builds on State.

Lifting state up (State) gives you one source of truth, but it has a cost: the data has to travel down as props through every component between the owner and the components that use it. A theme, the signed-in user, a locale, the reading list's dispatch: these are needed all over the tree, and threading them through layers that don't care about them is tedious and brittle.

Context lets a component provide a value to its whole subtree, and lets any descendant read it directly. It's simple to use and easy to misuse, because it has a specific re-render behavior that interviewers ask about: when a provider's value changes, every component that reads it re-renders. This chapter covers the API in React 19, that propagation rule and what to do about it, and when context is the wrong tool.

The problem: prop drilling#

The reading list has grown into a layout. Only Header and BookList need the entries, and only BookList and AddBook need dispatch, but everything in between has to accept and forward them.

Prop drilling
function App() {
  const [entries, dispatch] = useReducer(readingListReducer, initialEntries);
  return <Page entries={entries} dispatch={dispatch} />;
}

function Page({ entries, dispatch }: PageProps) {
  // Page uses neither. It just passes them on.
  return (
    <Layout entries={entries} dispatch={dispatch}>
      <Sidebar />
    </Layout>
  );
}

function Layout({ entries, dispatch, children }: LayoutProps) {
  return (
    <>
      <Header entries={entries} />
      <main>
        <BookList entries={entries} dispatch={dispatch} />
        <AddBook dispatch={dispatch} />
      </main>
      {children}
    </>
  );
}

Every intermediate component's props now mention data it doesn't use. Renaming a field or adding one means editing every layer. That's prop drilling.

Before reaching for context, try composition. If Page and Layout took children (or slot props) and App placed Header and BookList directly, the data would go straight to its consumers with no drilling at all (Components and props). Composition fixes more drilling than people expect. Context is for when the consumers really are deep and scattered, or when the value is truly app-wide.

The real API#

Three pieces: create a context, provide a value, read it.

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

// 1. Create it, with a default for components that have no provider above them.
const ThemeContext = createContext<"light" | "dark">("light");

// 2. Provide a value to a subtree. React 19: render the context itself.
function App() {
  return (
    <ThemeContext value="dark">
      <Toolbar />
    </ThemeContext>
  );
}

// 3. Read the nearest provider's value, anywhere below.
function Button() {
  const theme = useContext(ThemeContext); // or: use(ThemeContext)
  return <button className={theme}>Save</button>;
}
  • createContext(defaultValue) returns a context object. The default is used only when there's no provider above the reader. It doesn't change, so it isn't a fallback for "loading".
  • <ThemeContext value={...}> React 19.0 provides a value. Before React 19 you wrote <ThemeContext.Provider value={...}>, which still works; React has said it will deprecate Context.Provider in a future version. Providers nest, and a reader gets the nearest one above it. You can override a value for part of the tree by providing it again.
  • useContext(ThemeContext) reads the value. Like every hook, it has to be called unconditionally at the top level.
  • use(ThemeContext) React 19.0 also reads context, but use may be called inside conditions and loops, and after early returns. It's the same API that unwraps promises (Suspense and use).
function Heading({ children, hidden }: { children: ReactNode; hidden?: boolean }) {
  if (hidden) return null;
  const theme = use(ThemeContext); // fine after an early return; useContext isn't
  return <h2 className={theme}>{children}</h2>;
}

A component can't read a context it provides itself; useContext looks for providers above the component calling it.

Typing pattern: when there's no sensible default, type the context as T | null, default to null, and wrap the read in a custom hook that throws a clear error. Callers get a non-null type and a helpful message if they forget the provider:

const EntriesContext = createContext<Entry[] | null>(null);

export function useEntries() {
  const entries = use(EntriesContext);
  if (entries === null) throw new Error("useEntries must be used inside <ReadingListProvider>");
  return entries;
}
How React finds the nearest providerDeep dive

You can picture context as a stack maintained during rendering. When React begins rendering a provider, it pushes the provider's value; when it finishes that subtree, it pops it. A useContext call reads the top of the stack for that context, so it always sees the nearest provider. Because rendering a subtree happens between the push and the pop, siblings outside the provider see the previous value.

Reading also records a dependency: React stores on the reading fiber which contexts it read and what values it saw. That's what makes propagation possible. When a provider renders with a value that isn't Object.is-equal to the last one, React looks through the fibers below it for ones whose dependency list includes that context, and schedules them to re-render, even if every component between them bailed out. (React 19 does this search lazily: it only scans below a point where rendering would otherwise bail out, because a subtree that re-renders anyway will reach its readers on its own. The result is the same.)

The reading list, part 3: shared through context#

Here's the reading list with its reducer from useReducer, shared through two contexts: one for the entries, one for dispatch. A ReadingListProvider component owns the state and takes children, so the rest of the tree is written once in App with no props passed through. Each component is wrapped in Rendered so you can see who re-renders.

Reading list: reducer plus context
import { useState } from "react";
import { Rendered } from "guide-tools";
import { ReadingListProvider, useEntries, useReadingListDispatch } from "./ReadingListContext";

let nextId = 1000;

function Header() {
  const entries = useEntries();
  const unread = entries.filter((e) => !e.read).length;
  return (
    <Rendered label="Header">
      <strong>{unread} unread</strong>
    </Rendered>
  );
}

function BookList() {
  const entries = useEntries();
  const dispatch = useReadingListDispatch();
  return (
    <Rendered label="BookList">
      <ul style={{ listStyle: "none", padding: 0, margin: 0 }}>
        {entries.map((e) => (
          <li key={e.id}>
            <label>
              <input type="checkbox" checked={e.read} onChange={() => dispatch({ type: "toggled", id: e.id })} /> {e.title}
            </label>
          </li>
        ))}
      </ul>
    </Rendered>
  );
}

function AddBook() {
  const dispatch = useReadingListDispatch(); // reads only dispatch
  const [title, setTitle] = useState("");
  return (
    <Rendered label="AddBook">
      <form
        onSubmit={(e) => {
          e.preventDefault();
          if (!title.trim()) return;
          dispatch({ type: "added", id: nextId++, title: title.trim() });
          setTitle("");
        }}
      >
        <input value={title} onChange={(e) => setTitle(e.target.value)} placeholder="Add a book" /> <button>Add</button>
      </form>
    </Rendered>
  );
}

function Sidebar() {
  return <Rendered label="Sidebar">Reads no context.</Rendered>;
}

export default function App() {
  return (
    <ReadingListProvider>
      <Header />
      <BookList />
      <AddBook />
      <Sidebar />
    </ReadingListProvider>
  );
}

Toggle a book: Header and BookList flash, AddBook and Sidebar don't. Type in the input: only AddBook renders. Three things made that happen, and each is worth being able to explain:

  1. The provider takes children. When its state changes, ReadingListProvider re-renders, but the children elements were created by App, which didn't re-render. React reuses them and skips those components unless something else tells it to render them.
  2. Context tells it to. The entries value is a new array, so React finds every component that read EntriesContext and re-renders it. That's Header and BookList.
  3. dispatch lives in its own context. dispatch never changes identity, so DispatchContext's value never changes, and AddBook, which reads only that, isn't touched by a toggle. If both were in one { entries, dispatch } object, AddBook would re-render on every toggle.

This reducer-plus-two-contexts shape is the standard way to manage app-level state with only React, and it's what react.dev recommends for scaling up a reducer.

How a value change propagates#

A context value change reaching consumers
ReadingListProvidervalue = v1LayoutchildrenHeaderreads contextSidebarno contextBookListreads contextclay: renders this step
Step 1 of 5

ReadingListProvider keeps the list in state and renders <ReadingListContext value={...}>. Layout was passed in as children by App. Header and BookList read the context; Sidebar doesn't.

The rule, stated precisely: when a provider renders with a value that isn't Object.is-equal to its previous value, every component below it that reads that context re-renders. A few consequences:

  • There's no partial subscription. A component that reads { user, theme } and uses only user still re-renders when theme changes. Context has no selectors.
  • memo doesn't stop it. Wrapping an intermediate component in memo (Memoization) can stop a parent's re-render from cascading through props, but a component that reads a changed context re-renders regardless.
  • Identity is what's compared, not contents. A provider that builds its value inline, value={{ user, rename }}, makes a new object on every render of the provider, so every consumer re-renders every time the provider renders, even if nothing in the value changed.

Three fixes, in the order to try them:

  1. Keep the provider's own re-renders rare. Put the state in a dedicated provider component that takes children, as above. Then the provider only re-renders when that state changes.
  2. Split contexts by how often things change and by who reads them: state apart from dispatch or setters, fast-changing values apart from stable ones, unrelated concerns apart from each other.
  3. Memoize the value when it has to be an object built from several values: const value = useMemo(() => ({ user, rename }), [user]), with rename itself stable (a setter, dispatch, or useCallback). With the React Compiler this memoization happens automatically (The React Compiler).
Fix itThe badge that re-renders on theme changes

UserBadge only shows the user's name, but every theme toggle re-renders it (watch its render count). Fix it so toggling the theme leaves UserBadge alone, while Rename still updates it.

import { createContext, use, useState, type ReactNode } from "react";
import { Rendered } from "guide-tools";

type User = { name: string };
type UserValue = { user: User; rename: (name: string) => void };
type ThemeValue = { theme: "light" | "dark"; toggle: () => void };

const UserContext = createContext<UserValue | null>(null);
const ThemeContext = createContext<ThemeValue | null>(null);

function AppProviders({ children }: { children: ReactNode }) {
  const [user, setUser] = useState<User>({ name: "Ada" });
  const [theme, setTheme] = useState<"light" | "dark">("light");
  return (
    <UserContext value={{ user, rename: (name) => setUser({ name }) }}>
      <ThemeContext value={{ theme, toggle: () => setTheme((t) => (t === "light" ? "dark" : "light")) }}>
        {children}
      </ThemeContext>
    </UserContext>
  );
}

function UserBadge() {
  const { user } = use(UserContext)!;
  return (
    <Rendered label="UserBadge">
      <p>Signed in as {user.name}</p>
    </Rendered>
  );
}

function ThemeToggle() {
  const { theme, toggle } = use(ThemeContext)!;
  return (
    <Rendered label="ThemeToggle">
      <button onClick={toggle}>Theme: {theme}</button>
    </Rendered>
  );
}

function RenameButton() {
  const { rename } = use(UserContext)!;
  return <button onClick={() => rename("Grace")}>Rename</button>;
}

export default function App() {
  return (
    <AppProviders>
      <UserBadge />
      <ThemeToggle />
      <RenameButton />
    </AppProviders>
  );
}

When not to use context#

Context is a transport, not a state manager. It moves a value from a provider to readers; it doesn't store anything itself (your useState or useReducer does), and it has no selectors, caching or devtools. That makes it a great fit for some things and a poor fit for others.

Good fits:

  • Values that are read in many places and change rarely: theme, locale, the signed-in user, feature flags.
  • Dependency injection: an API client, an analytics object, a router.
  • Coordinating a small subtree, like a compound component (<Tabs> sharing the active tab with <Tab>), covered in Component patterns.
  • App-level state of modest size, with the reducer-plus-split-contexts pattern above.

Poor fits:

  • Values that change very often and have many readers, like mouse position, scroll offset or a text field's value. Every change re-renders every reader. A store with selectors (Build a store, Zustand) re-renders only components whose selected slice changed.
  • Avoiding a couple of levels of props. Passing props two levels down is explicit and fine. Context makes data flow implicit: a component's behavior now depends on where it's rendered.
  • Server data. Fetched data needs caching, refetching and invalidation; put it in a server-state library (Server state), which uses context internally only to provide the client.
  • Anything composition solves. Pass the component that needs the data as children or a slot instead.

Pitfalls#

Check your understanding#

PredictWhich theme?

What does each Label render?

const ThemeContext = createContext("light");

function Label({ name }: { name: string }) {
  return <p>{name}: {useContext(ThemeContext)}</p>;
}

export default function App() {
  return (
    <>
      <Label name="A" />
      <ThemeContext value="dark">
        <Label name="B" />
        <ThemeContext value="sepia">
          <Label name="C" />
        </ThemeContext>
        <Label name="D" />
      </ThemeContext>
    </>
  );
}
Quick checkuse or useContext?

What can `use(SomeContext)` do that `useContext(SomeContext)` can't?

Explain it out loudContext and re-renders

An interviewer asks: "If I put my app state in a context, what re-renders when it changes? How would you make it efficient?"

Interview angle

Say it in 30 seconds

Context lets a component provide a value to its whole subtree so descendants can read it without prop drilling. You create it with createContext, provide it in React 19 by rendering the context with a value prop, and read it with useContext or use, which can be called conditionally. The key behavior: when the provider's value changes by Object.is, every component that reads it re-renders, even through memo, and there are no selectors. So keep providers in their own components that take children, split state from dispatch, memoize object values, and use a store with selectors for high-frequency shared state.

What problem does context solve, and how do you use it in React 19?

basic

What re-renders when a context value changes?

intermediate

How do you keep a context from causing unnecessary re-renders?

senior

What happens if a provider passes value={{ user, setUser }}?

intermediate

When would you not use context for state?

senior

How is use(Context) different from useContext(Context)?

basic

Recap#

  • Context passes a value from a provider to any descendant without props. Try composition first; use context for widely read values or deep, scattered consumers.
  • React 19: provide with <Context value={...}> (Context.Provider still works), read with useContext or with use, which can be called conditionally. Readers get the nearest provider, or the default without one.
  • When the provided value changes by Object.is, every reader below re-renders, through memo, with no partial subscription.
  • Keep re-renders down with a dedicated provider component that takes children, split contexts (state apart from dispatch), and memoized values.
  • Context is a transport, not a state manager. For high-frequency, widely read state, use a store with selectors; for server data, a server-state library.

Sources#