Skip to content

Lesson 12 of 37State

Context

Pass data deep into the tree without prop drilling, combine context with a reducer, and know when a store fits better.

17 min read0/6 questions

Some data is needed almost everywhere: the current user, the theme, the language, a feature flag. Passing it as props through ten layers of components that do not use it is tedious and fragile. Context lets any component read a value from far above it directly. It is built into React, every app uses it somewhere, and knowing its performance trade-off is a common interview topic.

The problem: prop drilling

Imagine a page where the theme is chosen in App, but only a button deep inside needs it. Every component in between has to accept a theme prop and pass it on, even though it never uses it. This is called prop drilling.

Prop drilling vs context
Appowns themeThemeButtonuses themeNavthemeSidebarthemeCarduses themeArticlethemeMainthemeLayoutthemeroot

App owns theme, and only ThemeButton and Card actually use it.

1/3

Prop drilling a level or two is completely fine and often clearer, because you can see where data comes from. Context earns its place when many components at different depths need the same value.

createContext, a provider, and useContext

Context has three parts:

  1. Create it once, at module level, with a default value: const ThemeContext = createContext("light").
  2. Provide a value above the components that need it. In React 19 you render the context itself: <ThemeContext value="dark">...</ThemeContext>. (Before React 19 you wrote <ThemeContext.Provider value="dark">, which still works and which you will see in older code.)
  3. Read it in any component below with useContext(ThemeContext). React finds the closest provider above and returns its value. If there is none, you get the default.
React
import { createContext, useContext, useState } from "react"; type Theme = "light" | "dark";const ThemeContext = createContext<Theme>("light"); function ThemedButton({ children, onClick }: { children: string; onClick?: () => void }) { const theme = useContext(ThemeContext); const style = theme === "dark" ? { background: "#222", color: "#fff" } : { background: "#fff", color: "#222" }; return <button style={style} onClick={onClick}>{children}</button>;} function Toolbar({ onToggle }: { onToggle: () => void }) { // No theme prop here: Toolbar does not need to know. return ( <div style={{ display: "flex", gap: 6 }}> <ThemedButton>Save</ThemedButton> <ThemedButton onClick={onToggle}>Toggle theme</ThemedButton> </div> );} export default function App() { const [theme, setTheme] = useState<Theme>("light"); return ( <ThemeContext value={theme}> <Toolbar onToggle={() => setTheme(theme === "light" ? "dark" : "light")} /> <p>Current theme: {theme}</p> <ThemeContext value="dark"> <ThemedButton>Always dark (nearest provider wins)</ThemedButton> </ThemeContext> </ThemeContext> );}

When the provided value changes, every component that reads that context re-renders with the new value, however deep it is.

React 19 also added use(ThemeContext). It returns the same value as useContext, but unlike other hooks it may be called inside if statements and loops.

Quick check
A component calls useContext(ThemeContext). It sits inside <ThemeContext value="dark">, which sits inside <ThemeContext value="light">. The context was created with createContext("blue"). What does it get?
Need a nudge? A hint rules out a wrong answer.

Passing functions and objects: an auth example

A context value can be anything, including an object that bundles data with the functions to change it. A typical pattern wraps the provider in its own component and exposes a custom hook, so consumers never touch the context object directly.

React
import { createContext, useContext, useState } from "react";import type { ReactNode } from "react"; type User = { name: string };type Auth = { user: User | null; logIn: (name: string) => void; logOut: () => void }; const AuthContext = createContext<Auth | null>(null); function AuthProvider({ children }: { children: ReactNode }) { const [user, setUser] = useState<User | null>(null); const value: Auth = { user, logIn: (name) => setUser({ name }), logOut: () => setUser(null) }; return <AuthContext value={value}>{children}</AuthContext>;} function useAuth() { const auth = useContext(AuthContext); if (!auth) throw new Error("useAuth must be used inside <AuthProvider>"); return auth;} function Navbar() { const { user, logIn, logOut } = useAuth(); return user ? ( <p> Signed in as {user.name} <button onClick={logOut}>Log out</button> </p> ) : ( <button onClick={() => logIn("Ada")}>Log in as Ada</button> );} function Dashboard() { const { user } = useAuth(); return <h3>{user ? `Welcome back, ${user.name}` : "Please log in"}</h3>;} export default function App() { return ( <AuthProvider> <Navbar /> <Dashboard /> </AuthProvider> );}

Navbar and Dashboard never receive props, yet they stay in sync because they read the same context. The default null plus the check in useAuth turns "forgot the provider" into a clear error instead of a confusing undefined.

Predict the outputJavaScript

There is no provider anywhere above Label. What does it render?

const LangContext = createContext("en");

function Label() {
const lang = useContext(LangContext);
return <span>{lang}</span>;
}

<Label />
Need a nudge? Hints walk you through it.

React 19: the context is the provider

In React 19 you render the context object itself as the provider: <ThemeContext value="dark">. It is not a new feature so much as a simplification, but you will meet both forms in the same codebase for years, so know the details.

  • <Ctx.Provider value> still works in React 19; the React team has said it will be deprecated in a future version. The change is mechanical (a codemod or search-and-replace), so on a large codebase do it in its own pull request where the diff is easy to review.
  • <Ctx.Consumer> (a render-prop component) is legacy. Replace it with useContext or use when you touch the code.
  • Give each context a name in DevTools. By default every provider shows as Context.Provider or Context. Set ThemeContext.displayName = "ThemeContext" and the components tree becomes readable.
  • Type the "no provider" case honestly. If there is no sensible default (an auth object, a form's state), create the context with null and throw in the custom hook, as the auth example does. A fake default like createContext<Auth>({} as Auth) silently hides a missing provider until something calls logIn and crashes.

In apps with Server Components (the Next.js App Router), context belongs to the client side. Server Components cannot create or read context: there is no state on the server between requests to put in it. The standard structure is a client component that holds all the app's providers, rendered once near the root:

app/providers.tsx
"use client";
 
import { ThemeContext } from "@/lib/theme-context";
import { useState, type ReactNode } from "react";
 
export function Providers({ children }: { children: ReactNode }) {
  const [theme, setTheme] = useState<"light" | "dark">("light");
  return <ThemeContext value={theme}>{children}</ThemeContext>;
}
app/layout.tsx
import { Providers } from "./providers";
 
export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        <Providers>{children}</Providers>
      </body>
    </html>
  );
}

children here can still be Server Components. They are rendered on the server and passed through the client provider as already-rendered output, so wrapping the app in providers does not turn the whole tree into client code. Place providers as deep as the consumers allow: a provider used only by the checkout belongs in the checkout layout, not the root.

use(Context): reading context conditionally

useContext is a hook, so it follows the rules of hooks: top level only, never after an early return. React 19's use(Context) returns the same value but is allowed inside conditions and loops, because React does not track it by call order. It reads the context directly from the component's position in the tree.

That matters for components with an early exit:

ReactUseContextConditionally.tsx
import { createContext, use, useState } from "react"; const PermissionsContext = createContext<string[]>([]); function AdminBadge({ isVisible }: { isVisible: boolean }) { if (!isVisible) return null; // early return: useContext here would break the rules of hooks const permissions = use(PermissionsContext); // fine with use() return <p>Permissions: {permissions.join(", ") || "none"}</p>;} export default function App() { const [isVisible, setIsVisible] = useState(false); const [isAdmin, setIsAdmin] = useState(false); return ( <PermissionsContext value={isAdmin ? ["read", "write", "delete"] : ["read"]}> <label><input type="checkbox" checked={isVisible} onChange={(e) => setIsVisible(e.target.checked)} /> Show badge</label> <label><input type="checkbox" checked={isAdmin} onChange={(e) => setIsAdmin(e.target.checked)} /> Admin</label> <AdminBadge isVisible={isVisible} /> </PermissionsContext> );}

use still has limits. It must be called inside a component or hook, during render, not in an event handler or effect. And like useContext, it reads from the closest provider above the component that calls it. A provider a component renders in its own output does not affect what that same component reads:

Predict the outputJavaScript

What does Panel render?

const SizeContext = createContext("small");

function Panel() {
const size = useContext(SizeContext);
return (
  <SizeContext value="large">
    <span>{size}</span>
  </SizeContext>
);
}

<SizeContext value="medium">
<Panel />
</SizeContext>
Need a nudge? Hints walk you through it.

The same rule explains a common bug: a provider component that tries to read its own context in the same function always gets the outer value or the default.

Context plus a reducer

For app-wide state with real update logic, combine the two previous lessons: keep the state in useReducer at the top, and put both the state and dispatch in context. Any component can then read the state or dispatch actions without drilling.

const TasksContext = createContext<Task[]>([]);
const TasksDispatchContext = createContext<Dispatch<TaskAction>>(() => {});
 
export function TasksProvider({ children }: { children: ReactNode }) {
  const [tasks, dispatch] = useReducer(tasksReducer, []);
  return (
    <TasksContext value={tasks}>
      <TasksDispatchContext value={dispatch}>{children}</TasksDispatchContext>
    </TasksContext>
  );
}
 
// anywhere below:
const dispatch = useContext(TasksDispatchContext);
dispatch({ type: "added", id: 7, text: "Ship it" });

Splitting state and dispatch into two contexts is deliberate: dispatch never changes, so components that only dispatch (an "Add task" form) do not re-render when the task list changes.

Splitting state and dispatch contexts

The reducer example above used two contexts on purpose. It is worth seeing why, because this split is the cheapest performance fix context offers and it shows up in most codebases that use context for state. Open the console and add a few tasks. Then click Re-render App to see the baseline.

ReactSplitContexts.tsx
import { createContext, memo, useContext, useReducer, useState } from "react";import type { Dispatch, ReactNode } from "react"; type Task = { id: number; text: string };type Action = { type: "added"; text: string } | { type: "cleared" }; function tasksReducer(tasks: Task[], action: Action): Task[] { switch (action.type) { case "added": return [...tasks, { id: tasks.length + 1, text: action.text }]; case "cleared": return []; }} const TasksContext = createContext<Task[]>([]);const TasksDispatchContext = createContext<Dispatch<Action>>(() => {}); function TasksProvider({ children }: { children: ReactNode }) { const [tasks, dispatch] = useReducer(tasksReducer, []); return ( <TasksContext value={tasks}> <TasksDispatchContext value={dispatch}>{children}</TasksDispatchContext> </TasksContext> );} const AddTask = memo(function AddTask() { const dispatch = useContext(TasksDispatchContext); // never changes console.log("AddTask rendered"); return ( <div style={{ display: "flex", gap: 6 }}> <button onClick={() => dispatch({ type: "added", text: "New task" })}>Add task</button> <button onClick={() => dispatch({ type: "cleared" })}>Clear</button> </div> );}); const TaskList = memo(function TaskList() { const tasks = useContext(TasksContext); // changes on every add console.log("TaskList rendered"); return <ul>{tasks.map((t) => <li key={t.id}>{t.text} #{t.id}</li>)}</ul>;}); export default function App() { const [n, setN] = useState(0); return ( <TasksProvider> <button onClick={() => setN(n + 1)}>Re-render App ({n})</button> <AddTask /> <TaskList /> </TasksProvider> );}

Clicking Add task logs only TaskList rendered. AddTask reads only the dispatch context, and dispatch from useReducer is the same function forever, so React has no reason to touch it. Clicking Re-render App logs nothing at all: both children are memo and receive no props, and no context they read changed.

Two details make this work, and both are easy to break:

  • The provider takes children. TasksProvider re-renders when tasks change, but children was created by App, which did not re-render, so React reuses those elements and only updates the context readers. If the provider rendered <AddTask /> itself, its children would re-render with it (unless memoized).
  • Each context value is stable on its own. dispatch is stable for free. If you put a hand-written object of functions in the actions context, build it with useMemo so it keeps its identity, or the split buys nothing.
Quick check
A CartProvider provides value={{ items, addItem, removeItem }} in one context. A BuyButton on every product card only uses addItem, and adding an item makes all 60 buttons re-render. What is the best fix?
Need a nudge? A hint rules out a wrong answer.

The performance caveat

When a provider's value changes, every component that reads that context re-renders. Two consequences:

  • One big context for everything is slow. If the theme, the user and the cart all live in one object, changing the cart re-renders every component that only wanted the theme. Split unrelated data into separate contexts.
  • A new object every render counts as a change. value={{ user, logIn }} creates a fresh object each time the provider re-renders, so all consumers re-render even if user did not change. Wrap it in useMemo (covered in the performance lesson) or let the React Compiler memoise it for you.
Match the pairs0/4 matched

Match each situation to the best tool.

Choose an item, then its match on the other side.

When to reach for a store instead

Context is a way to pass a value, not a state manager. It works well for values that change rarely (theme, locale, signed-in user). When shared state is large and changes often, like a big editor, a dashboard with live filters, or a shopping cart touched from everywhere, teams usually reach for a store:

ToolWhat it isWhy teams pick it
ZustandA tiny store library (about 1 KB) with a hook APIComponents subscribe to just the slice they read, so unrelated updates do not re-render them. Very little boilerplate.
Redux ToolkitThe modern, official way to write ReduxReducers and actions (the pattern you just learned), great dev tools, time-travel debugging, common in large codebases.
TanStack QueryA server-state cacheMost "global state" is really API data. It handles caching, loading and refetching.

Start with local state, lift it when needed, use context for widely read values, and add a store only when you feel real pain.

Quick check
A CartContext provides { items, add } as value={{ items, add }} from a component that re-renders every second for a clock. What happens to components that read CartContext?
Need a nudge? A hint rules out a wrong answer.

Context at work: patterns and pitfalls

A few things you will see, and be asked about, on a real team.

Context for dependencies, not just data. Context is a clean way to inject things a component needs but should not import directly: an API client, an analytics tracker, a feature-flag reader, a date formatter with the user's locale. In tests you provide a fake, with no module mocking:

const AnalyticsContext = createContext<Analytics>(noopAnalytics);
export const useAnalytics = () => useContext(AnalyticsContext);
 
// In a test:
render(
  <AnalyticsContext value={fakeAnalytics}>
    <CheckoutButton />
  </AnalyticsContext>,
);
expect(fakeAnalytics.track).toHaveBeenCalledWith("checkout_started");

Keep high-frequency values out of context. The mouse position, scroll offset, a timer ticking every 100 ms, or the text of a field as the user types would re-render every consumer many times a second. Keep those in local state, a ref, or a store with selectors (Performance covers selectors).

Several providers compose by nesting. It is normal to see five providers stacked at the root. If it becomes unreadable, keep them in one Providers component rather than inventing a "compose providers" helper. The order matters only when one provider reads another, such as an auth provider that needs the API client: the dependency goes outside.

Context does not cross React roots. A widget rendered with a separate createRoot (for example by a non-React page) does not see providers from the main app. Portals are different: content rendered through createPortal still reads context from where the portal is in the React tree, which is why modals rendered into document.body can still read the theme.

Default values are for tests and stories, not for production. If a component works without a provider because of a convenient default, nobody notices when the provider is missing in one route. For anything with behaviour, prefer null plus a hook that throws a clear error.

ChallengeMedium

Theme with context

App owns a theme ("light" or "dark") and the deep components ThemeToggle and Message need it. The middle components Toolbar and Panel must not take any props. Use context.

  • Message renders <p className="message">Current theme: light</p> (with the current theme).
  • ThemeToggle renders a button reading Switch to dark when the theme is light, and Switch to light when it is dark. Clicking it switches the theme.

Provide an object { theme, toggle } through ThemeContext, and read it with useContext.

React
import { createContext, useContext, useState } from "react"; type Theme = "light" | "dark";type ThemeValue = { theme: Theme; toggle: () => void }; const ThemeContext = createContext<ThemeValue | null>(null); function ThemeToggle() { // read the context and render the button return <button>Switch theme</button>;} function Message() { // read the context and show the theme return <p className="message">Current theme: ?</p>;} function Toolbar() { return ( <div> <ThemeToggle /> </div> );} function Panel() { return ( <section> <Message /> </section> );} export default function App() { const [theme, setTheme] = useState<Theme>("light"); return ( <div> <Toolbar /> <Panel /> </div> );}
Key terms
prop drilling
Passing a prop through many components that do not use it, just to reach a deep child.
context
A way to make a value available to every component below a provider, without passing props.
provider
<MyContext value={...}> (React 19) or <MyContext.Provider>: supplies the value to its subtree.
useContext
Reads the value from the closest provider above, or the default from createContext if there is none.
state store
A library like Zustand or Redux Toolkit holding shared state outside components, with subscriptions to slices.
use(Context)
React 19's way to read context that, unlike useContext, may be called inside conditions and loops.
dispatch context
A separate context holding only the stable dispatch or actions, so components that only trigger changes do not re-render on state changes.
displayName
A property you set on a context so React DevTools shows a readable name for its providers.