Skip to main content

Context and useContext

Context lets a component read information from the closest matching provider above it without every intermediate component forwarding that value as a prop.

The API is simple. The architectural question is harder:

Is this value really part of the surrounding environment for a subtree, or are we using Context to avoid deciding who owns the state?

Start with props​

Props should remain the default way to make dependencies explicit.

Props keep local dependencies visible
ProductPage
ProductCard
Price

If only a small chain needs currency, props may be clearer than introducing a shared environment.

function ProductPage({product, currency}) {
return <ProductCard product={product} currency={currency} />;
}

The problem Context solves​

Context becomes useful when the same surrounding information is needed deep in a subtree and intermediate components would otherwise forward it without using it.

Context creates a tree-scoped environment
Theme provider
owns the value boundary for this subtree
Header β†’ IconButton
IconButton reads theme directly.
Settings β†’ Preview β†’ Card
Card reads the same nearest theme.

Common candidates include theme, locale, session/environment data, feature configuration, form coordination, and feature state/dispatch.

Creating a context​

import {createContext} from 'react';

export const ThemeContext = createContext('light');

The context object is a channel, not mutable storage. The default value is used only when no matching provider exists above the consumer.

Providing a value in React 19​

React 19+

function App() {
return (
<ThemeContext value="dark">
<Dashboard />
</ThemeContext>
);
}

Older code commonly uses <ThemeContext.Provider value="dark">. You still need to recognize that syntax for maintenance, but React 19 can render the context object directly as the provider.

Reading context​

function Toolbar() {
const theme = useContext(ThemeContext);
return <div className={`toolbar toolbar-${theme}`}>Toolbar</div>;
}
How useContext resolves a valueLookup follows the rendered component tree, not imports or file structure.
1component calls useContext(Context)
2React checks providers above it
3closest matching provider wins
4consumer receives current value

Closest provider wins​

<ThemeContext value="light">
<Header />

<ThemeContext value="dark">
<AdminPanel />
</ThemeContext>
</ThemeContext>

Header reads light; AdminPanel reads dark.

Nested providers create scoped overrides
Outer branch
Header β†’ light
Nested branch
AdminPanel β†’ dark

Providers must already be above consumers​

This component reads before the provider it returns exists above that read:

function Page() {
const theme = useContext(ThemeContext);

return (
<ThemeContext value="dark">
<Dashboard />
</ThemeContext>
);
}

The provider affects descendants such as Dashboard, not Page's earlier useContext call.

Default values​

const ThemeContext = createContext('light');

With no provider above, the consumer gets 'light'. If a provider explicitly passes undefined, the consumer gets undefined; React does not fall back to the default.

For required application contexts, null plus a validating custom Hook is often safer:

const AuthContext = createContext(null);

export function useAuth() {
const value = useContext(AuthContext);

if (value === null) {
throw new Error('useAuth must be used inside AuthProvider');
}

return value;
}

Context distributes state; it does not create state​

export function ThemeProvider({children}) {
const [theme, setTheme] = useState('light');

return (
<ThemeContext value={{theme, setTheme}}>
{children}
</ThemeContext>
);
}
Ownership vs distribution
OWNERuseState / useReducer
Creates and transitions React state.
DISTRIBUTORContext
Makes the owner's value accessible to descendants.

A provider component can combine these responsibilities, but they remain conceptually separate.

Context updates and rendering​

A consumer that reads a context subscribes to that context value. When the provider's value changes according to Object.is, React can update those consumers.

<ThemeContext value={{theme, setTheme}}>

That object is newly created when the provider renders. This is not automatically a performance problem; measure first. It does mean value identity is relevant when a context has many consumers or changes frequently.

memo does not block context updates because context is another input to the component, separate from props.

Context is tree-scoped, not automatically global​

One Context type can have independent provider branches
StorefrontProvider
Storefront descendants read one value/state instance.
AdminProvider
Admin descendants can read another value/state instance.

Think tree-scoped dependency, not β€œglobal variable.”

What belongs in Context?​

Good candidates often share these properties:

  • many descendants need the value;
  • it represents a surrounding environment or feature state;
  • prop forwarding creates real noise;
  • consumers should intentionally depend on this provider boundary.

Use props when the relationship is naturally parent β†’ child, only a few consumers need the value, or explicit dependencies improve reusability.

Composition can remove prop drilling​

Before Context, ask whether composition can move the consumer closer to the owner:

<Layout header={<UserMenu user={user} />} />

Now Layout does not need to receive and forward user merely for UserMenu.

Avoid one giant application Context​

<AppContext value={{
user,
products,
cart,
theme,
notifications,
filters,
settings,
}}>

This creates broad coupling and hides ownership.

Prefer domain-shaped provider boundaries
AuthProvider
ThemeProvider
CartProvider
FeatureProvider

Split providers by coherent ownership/change boundaries, not by arbitrary file size.

Context is not a server-state cache​

Context can transport remote data, but it does not by itself provide cache lifetime, deduplication, staleness, invalidation, retries, background refresh, or mutation coordination.

Server-state tools/framework APIs solve a different lifecycle problem.

Balanced dependency design​

Different mechanisms for different dependency scopes
Props
Local explicit parent β†’ child dependencies.
Context
Broad feature/environment dependency for a subtree.
Local state
Keep ownership close to where values actually change.

Debugging Context​

If a consumer gets the wrong value, check whether the provider is actually above it, whether a nearer provider overrides it, whether the provider supplies value, whether a default masks a missing provider, and whether provider/consumer import the exact same context object.

Production pattern: provider + custom Hook​

const CartContext = createContext(null);

export function CartProvider({children}) {
const [items, setItems] = useState([]);

return (
<CartContext value={{items, setItems}}>
{children}
</CartContext>
);
}

export function useCart() {
const context = useContext(CartContext);

if (context === null) {
throw new Error('useCart must be used inside CartProvider');
}

return context;
}

Benefits include validated provider requirements, fewer direct Context imports, and a stable feature API that can evolve internally.

Context decision​

Should this dependency use Context?
Only a small explicit parent β†’ child chain needs itPrefer props
Composition can place the consumer directly where the owner already has the dataPrefer composition
Many descendants need one coherent subtree environment/feature dependencyContext is a strong candidate
The real problem is server caching or fine-grained external subscriptionsChoose the tool that owns that lifecycle instead

Exercise​

Build a theme system with nested providers, a useTheme Hook, a toolbar that reads the nearest theme, and a toggle that updates only one provider subtree. Explain which component owns the state and what Context contributes.

Interview questions​

Junior: What problem does Context solve?

Mid-level: Why is Context not automatically a replacement for props or a state-management library?

Senior: How would you choose provider boundaries in a large application, and what rendering/coupling trade-offs would you inspect before optimizing Context?

Summary​

Context design flow
1start with explicit props
2identify a real subtree-wide dependency
3place provider above consumers
4keep state ownership explicit
5scope providers deliberately

References​

Next​

Continue with Context Architecture and Performance.