The Context API

The Context API in React: --- A large office building pipes background audio through ceiling speakers, and it is wired in zones.


The Analogy: A Building's Zoned Background-Audio System

A large office building pipes background audio through ceiling speakers, and it is wired in zones. Each floor has a zone amplifier tuned to a station, and every speaker in that zone plays whatever the amplifier is fed. A person standing anywhere on the floor simply hears the zone's audio -- they do not carry a personal radio, and nobody walks from desk to desk handing each worker a headphone cable. The sound fills the space; being present in the zone is enough to receive it.

Contrast that with the tedious alternative the wiring replaced: running a dedicated cable from the source, through every intervening room, to each individual listener. In that scheme a room in the middle that does not even want audio still has to carry the cable through so the far room can hear. Threading a signal through every layer that does not care about it, just to reach the layers that do, is exactly the chore the zone system abolishes.

Zones nest, and the nearest one wins. A conference room inside a floor can have its own small amplifier; step inside and you hear the room's station instead of the floor's, and step back out and the floor's audio returns. An area with no amplifier anywhere above it falls back to the building-wide default piped in from the lobby feed. So what any listener hears is decided by a simple rule: the closest enclosing amplifier, or the building default if there is none.

The system's weak spots are all about the shared feed. Retune a zone's amplifier and every listener in that zone is interrupted at once, whether or not they were paying attention. An amplifier that nervously flips its dial every few seconds -- even landing on the very same station each time -- disrupts the whole zone for no benefit. And wiring the entire building as one giant zone means every trivial adjustment blares to every floor simultaneously, when a change on the third floor should never have reached the tenth.

Syntax or Core Structure

Context has three moving parts: you create a context with a default, wrap a subtree in its Provider to supply a value, and read the value anywhere below with useContext. No component in between has to know the value exists.

import { createContext, useContext } from "react";

// 1. Create -- the argument is the default used when there is no Provider above.
const ThemeContext = createContext("light");

function App() {
  // 2. Provide -- everything inside sees value="dark".
  return (
    <ThemeContext.Provider value="dark">
      <Toolbar />
    </ThemeContext.Provider>
  );
}

function Toolbar() {
  // Toolbar neither reads nor forwards the theme -- it just renders children.
  return <ThemedButton />;
}

function ThemedButton() {
  // 3. Consume -- reaches past Toolbar to the nearest Provider.
  const theme = useContext(ThemeContext);
  return <button className={theme}>I am {theme}</button>;
}

That JSX renders in a browser, so it has no console output. The behaviour that matters is the resolution rule: a consumer reads the nearest enclosing Provider, or the default when none exists. That rule is a pure function of the stack of Providers above the consumer, so we can model it exactly and run it:

// Resolve a consumer's value from the Providers enclosing it (outer -> inner).
function readContext(providerStack, defaultValue) {
  return providerStack.length > 0
    ? providerStack[providerStack.length - 1]  // nearest = innermost = last
    : defaultValue;
}

const DEFAULT = "light";
console.log("no provider:", readContext([], DEFAULT));
console.log("one provider:", readContext(["dark"], DEFAULT));
console.log("nested:     ", readContext(["dark", "solarized"], DEFAULT));

Output:

no provider: light
one provider: dark
nested:      solarized

Trace it by hand. An empty stack has length 0, so readContext returns the default "light" -- this is the lobby with no amplifier. The stack ["dark"] returns its last element "dark". The nested stack ["dark", "solarized"] also returns its last element, "solarized": the inner Provider sits closest to the consumer, so it wins over the outer one. That single "return the last, else the default" line is the whole of context lookup.

Technical Depth: How a Value Reaches a Consumer, and What a Change Costs

Nearest Provider wins; the default fills the gap

Because lookup only cares about the closest enclosing Provider, two consumers at different depths of the same tree can read different values at the same instant. The table lists three listeners in one building and the amplifier stack above each:

Consumer locationEnclosing Providers (outer -> inner)Value read
lobby(none)default
floor 3darkdark
room 3Adark, high-contrasthigh-contrast

The lobby has nothing above it and falls to the default. Floor 3 sits under one amplifier and hears dark. Room 3A sits under both, and the inner high-contrast amplifier is nearest, so it overrides dark for anyone inside that room -- without changing what floor 3 hears one step outside the door.

A guard hook makes a missing Provider loud

The nearest-Provider rule has a quiet edge: when there is no Provider at all, useContext returns the default instead of complaining. If that default is a plausible value, a consumer mounted outside its Provider keeps working with the wrong data and nobody notices. A custom hook can turn that silent fallback into a loud error, so the default stays a true "no Provider" signal rather than accidental configuration:

// A guarded reader: no Provider is an error, not a silent default.
function useThemeGuarded(providerStack) {
  if (providerStack.length === 0) {
    return "ERROR: useTheme used outside ThemeProvider";
  }
  return providerStack[providerStack.length - 1];
}

console.log(useThemeGuarded([]));
console.log(useThemeGuarded(["dark"]));

Output:

ERROR: useTheme used outside ThemeProvider
dark

With an empty stack the guard reports the mistake immediately instead of handing back a default that looks fine; with a Provider present it behaves exactly like the plain reader and returns dark. In real code the guard throws rather than returning a string, which stops the misuse at the first render instead of letting wrong data flow downstream.

A changing value re-renders every consumer

When a Provider's value changes identity, every consumer of that context re-renders -- not just the ones whose displayed field changed. React compares the old and new value with Object.is; equal means the consumers can skip, different means they all re-run.

function broadcast(consumers, oldValue, newValue) {
  const changed = !Object.is(oldValue, newValue);
  return consumers
    .map(function (name) { return name + ": " + (changed ? "re-render" : "skip"); })
    .join("\n");
}

console.log("same value:");
console.log(broadcast(["Toolbar", "Sidebar"], "dark", "dark"));
console.log("changed value:");
console.log(broadcast(["Toolbar", "Sidebar"], "dark", "light"));

Output:

same value:
Toolbar: skip
Sidebar: skip
changed value:
Toolbar: re-render
Sidebar: re-render

Feeding the amplifier the same station ("dark" to "dark") is Object.is equal, so changed is false and both listeners skip. Retuning it to "light" is a real change, so every listener in the zone is interrupted at once. Note it is all consumers, together -- context does not let one consumer subscribe to just part of the value.

A new object each render defeats the skip

The skip only happens when the value is Object.is-equal across renders. Primitives like the strings above compare by content, but an object or array literal built inside the Provider is a brand-new identity every render, even when its contents are identical:

const render1 = { theme: "dark" };
const render2 = { theme: "dark" };  // same contents, new identity
console.log("Object.is:", Object.is(render1, render2));

Output:

Object.is: false

Two objects with identical contents are not the same object, so Object.is reports false. A Provider that writes value={{ theme }} inline hands its consumers a fresh identity on every single render -- the nervous amplifier flipping its dial to the same station -- and forces the whole zone to re-render for nothing. The fix is to make the value stable, which the Real World Example measures next.

Real World Example: An Auth Provider That Re-Renders the Whole App

A common context is authentication: one AuthProvider near the top of the tree holds the current user and a login function, and any screen deep inside reads them with useAuth. The intent is that consumers re-render only when the user actually changes -- logs in, logs out, updates a profile. In practice a very common version of this provider re-renders every consumer on every render of the app, because of one line.

// AuthProvider hands consumers value={{ user, login }}.
// The user data below never changes across these passes; only the app re-renders.
function renderPasses(passes, memoized) {
  const user = { name: "Ada" };  // identical user data every pass
  let lastValue = null;
  const log = [];
  for (let i = 1; i <= passes; i++) {
    const value = memoized
      ? (lastValue || { user: user })  // stable: reuse the first object
      : { user: user };                // FLAW: a brand-new object each pass
    const changed = !Object.is(value, lastValue);
    log.push("pass " + i + ": consumers " + (changed ? "re-render" : "skip"));
    lastValue = value;
  }
  return log.join("\n");
}

console.log("inline object value:");
console.log(renderPasses(3, false));
console.log("memoized value:");
console.log(renderPasses(3, true));

Output:

inline object value:
pass 1: consumers re-render
pass 2: consumers re-render
pass 3: consumers re-render
memoized value:
pass 1: consumers re-render
pass 2: consumers skip
pass 3: consumers skip

Follow the inline branch. Each pass builds { user } fresh, so value is a new identity every time; Object.is against the previous value is always false, so changed is true and the consumers re-render on all three passes -- even though user was the same { name: "Ada" } throughout. The memoized branch builds the object once on pass 1 and reuses it on passes 2 and 3, so Object.is is true and the consumers skip. The only difference is identity stability, not the data.

In real code the memoized branch is const value = useMemo(() => ({ user, login }), [user, login]). That collapses the needless re-renders down to the passes where user or login genuinely changed. The auth data drives real screens -- a header avatar, a route guard, a settings form -- so an unmemoized provider quietly re-renders all of them on unrelated state changes anywhere above it.

The design flaw in the shown code is precisely that inline value={{ user, login }}: it allocates a new object identity on every render, so Object.is always sees a change and every consumer re-renders regardless of whether the user moved. Memoizing the value fixes it -- but only if login is itself stable (wrap it in useCallback), otherwise the memo's dependencies change each render and you are back where you started. And even a perfectly memoized context still re-renders all consumers on a genuine change; for a value that changes many times a second, the honest fix is to split it into a smaller, hotter context or reach for a dedicated store rather than one building-wide zone.

Common Mistakes

  1. Reaching for context for everything. Context is for data a whole subtree genuinely shares. State that only one branch uses belongs in that branch; globalizing it makes the component harder to move and re-renders unrelated consumers.
  1. Passing a new object or array literal as the value each render. value={{ user, login }} is a fresh identity every render, so every consumer re-renders even when nothing changed. Memoize the value.
  1. Forgetting the Provider and silently getting the default. With no Provider above, useContext returns the createContext default. If that default looks plausible, the bug hides -- the screen just shows stale or wrong data with no error.
  1. Cramming unrelated state into one context. When theme, user, and cart all live in one value, changing any one of them re-renders every consumer of the others. Split by concern.
  1. Expecting field-level subscriptions. useContext re-renders on any change to the value's identity, not just the field you read. Reading only value.user does not spare you a re-render when value.cart changes in the same object.
  1. Treating the default as real configuration. The default is a fallback for "no Provider," best used as a sensible neutral or a guard that throws in development. Shipping real config only as the default means components work by accident until someone removes a Provider.
  1. Calling useContext conditionally. Like every hook, useContext must run at the top level in the same order every render. Putting it inside an if or a loop breaks the rules of hooks.
  1. Mutating the value object instead of replacing it. Editing value.user.name in place does not change the value's identity, so consumers may not re-render; when they do re-render for another reason they read the mutated data unpredictably. Always provide a new object when the data truly changes.
  1. Stacking many Providers into "provider hell." A dozen nested <A.Provider><B.Provider>... wrappers are hard to read. Compose them into a single AppProviders component instead of nesting them inline in the app root.

Best Practices

  • Use context for genuinely shared, slow-changing data such as theme, current user, or locale -- not for values that change many times a second.
  • Memoize the Provider value with useMemo, and stabilize any functions you put in it with useCallback, so consumers skip re-renders when the data is unchanged.
  • Split contexts by concern, so a change to one (say, theme) does not re-render consumers that only care about another (say, cart).
  • Give createContext a meaningful default, or export a custom hook that throws a clear error when used outside its Provider.
  • Keep frequently-changing values out of a wide context; colocate them with the component that owns them or use a dedicated store.
  • Wrap the Provider and its logic in a custom provider component, and expose a useX hook so consumers never touch the raw context object.
  • Keep every hook, including useContext, at the top level of the component so it runs in the same order on every render.
  • Never mutate the value in place; provide a fresh object whenever the shared data genuinely changes, and leave it identical when it does not.

Practice Exercises

  1. Using the readContext model, state the value read for the stacks [], ["dark"], and ["dark", "hc"] with default "light", and name which Provider (or the default) won in each case.
  1. Run renderPasses(3, false) and renderPasses(3, true) on paper. Explain why the inline branch re-renders on all three passes while the memoized branch skips passes 2 and 3, even though user is identical throughout.
  1. Given a lobby with no Provider, a floor under a "dark" Provider, and a room inside that floor under a "high-contrast" Provider, write the value each of the three consumers reads and justify each with the nearest-Provider rule.
  1. Take a component that prop-drills a user object through three intermediate layers that never use it. Rewrite it to provide user once with a Provider and consume it directly with useContext, and describe what each intermediate layer no longer has to do.