Context
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.
Three steps
1. Create the context
// 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:
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
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:
<ThemeContext value="dark">
<Page />
<ThemeContext value="light">
<Footer /> {/* sees "light" */}
</ThemeContext>
</ThemeContext>- When a provider’s
valuechanges, 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.
// 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;
}// 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
nulldefault 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:
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:
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
childreninstead (see Children and composition). Often that removes the drilling entirely.
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.
import { createContext, useContext, useState } from 'react';
const ThemeContext = createContext(null);
export function ThemeProvider({ children }) {
// your code here
}
export function useTheme() {
// your code here
}import { createContext, useContext, useState } from 'react';
const ThemeContext = createContext(null);
export function ThemeProvider({ children }) {
const [theme, setTheme] = useState('light');
function toggleTheme() {
setTheme((t) => (t === 'light' ? 'dark' : 'light'));
}
return <ThemeContext value={{ theme, toggleTheme }}>{children}</ThemeContext>;
}
export function useTheme() {
const ctx = useContext(ThemeContext);
if (!ctx) {
throw new Error('useTheme must be used inside <ThemeProvider>');
}
return ctx;
}
export function ThemeToggle() {
const { theme, toggleTheme } = useTheme();
return (
<button onClick={toggleTheme}>
Switch to {theme === 'light' ? 'dark' : 'light'} mode
</button>
);
}
export function Card({ children }) {
const { theme } = useTheme();
return <div className={theme === 'dark' ? 'card card-dark' : 'card'}>{children}</div>;
}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.