Explain it simply
Explain it simply
Imagine a notice at a building's entrance: "Today the Wi-Fi password for the whole building is sunshine". Nobody has to pass the message from floor to floor; any room can simply look at the notice.
React context is that notice. A component high in the tree provides a value, and any component below it, however deep, can read it directly with useContext. The components in between no longer have to hand the value along.
Problem → Why → Solution
The problem: passing props that nobody in between uses
App knows the signed-in user and UserMenu displays it. Layout and Sidebar sit in between, so user has to travel through both of them, even though neither uses it. This is called prop drilling. Want to add the user's avatar or rename the prop? You edit all four components.
function App() {
const user = { name: 'Aye' };
return <Layout user={user} />;
}
function Layout({ user }) { // does not use user
return <Sidebar user={user} />;
}
function Sidebar({ user }) { // does not use user either
return <UserMenu user={user} />;
}
function UserMenu({ user }) {
return <p>Signed in as {user.name}</p>;
}Why is this a problem?
Props only travel from a parent to its direct child. As the tree gets deeper, the components in between have to know about data that is not their concern, and they become harder to reuse. Context lets App provide the value and UserMenu read it directly with useContext, so Layout and Sidebar no longer know about user at all.
Core concept: create, provide, read
Context takes three steps. First, create it outside any component, at module level: const ThemeContext = createContext('light');, where the argument is the default value. Second, provide a value by wrapping part of the tree: <ThemeContext value="dark">...</ThemeContext>. That spelling is new in React 19; the older <ThemeContext.Provider value="dark"> still works, but React plans to deprecate it in a future version. Third, read it in any component below with const theme = useContext(ThemeContext);.
useContext searches upward from the calling component and returns the value of the nearest provider. Providers can be nested, and an inner provider overrides the outer value for its own subtree. You only get the default value from createContext when there is no provider above at all. A component does not see a provider that it renders in its own return; a provider only affects the components below it.
A context value is not state by itself. To make it changeable, keep useState in the component that renders the provider, and pass both the value and a setter, or a function like toggle, through the context. Whenever the provider's value changes, every component that reads that context re-renders, even if a component in between is wrapped in memo.
Context is not a global variable: it is scoped to the subtree below a provider, so tests can supply a different value and each screen can have its own provider. Still, when a prop only passes through two levels, plain props are clearer, because you can see where the data comes from.
- createContext(default) at module level
- Wrap a subtree in <Ctx value>
- useContext searches upward
- Nearest value, else the default
When the value changes, every reader re-renders.
General pattern
const SomeContext = createContext(defaultValue); // module level
function Parent() {
return (
// React 19: <SomeContext value>; older: <SomeContext.Provider value>
<SomeContext value={providedValue}>
<DeepChild />
</SomeContext>
);
}
function DeepChild() {
const value = useContext(SomeContext); // nearest provider's value
}Create the context once outside any component, provide a value high in the tree, and read it with useContext anywhere below. In React 18 and earlier you write <SomeContext.Provider value> instead.
Example: a theme context and its default
ThemeLabel is rendered twice: once inside a "dark" provider and once outside any provider. The component code is identical, but its position in the tree gives different results. The example uses React 19's <ThemeContext value> spelling.
import { createContext, useContext } from 'react';
const ThemeContext = createContext('light');
function ThemeLabel() {
const theme = useContext(ThemeContext);
return <p>Current theme: {theme}</p>;
}
export default function App() {
return (
<>
<ThemeContext value="dark">
<ThemeLabel />
</ThemeContext>
<ThemeLabel />
</>
);
}Code breakdown
- Line 3
const ThemeContext = createContext('light');The context is created once, outside any component. 'light' is the default used only when no provider is found.
- Line 6
const theme = useContext(ThemeContext);ThemeLabel needs no props; it searches up the tree and takes the value of the nearest ThemeContext provider.
- Line 13
<ThemeContext value="dark">In React 19 the context object itself renders as a provider. The ThemeLabel inside receives "dark".
- Line 16
<ThemeLabel />This ThemeLabel has no provider above it, so it falls back to the default, 'light'.
Two paragraphs render:
Current theme: dark
Current theme: lightMaking context updatable: state in the provider
ThemeProvider owns the state and provides theme and toggle together as one object. useMemo reuses the same object while theme is unchanged, so consumers do not re-render needlessly when ThemeProvider re-renders for some other reason.
import { createContext, useMemo, useState } from 'react';
export const ThemeContext = createContext(null);
export function ThemeProvider({ children }) {
const [theme, setTheme] = useState('light');
const value = useMemo(() => ({
theme,
toggle: () => setTheme((t) => (t === 'light' ? 'dark' : 'light')),
}), [theme]);
return <ThemeContext value={value}>{children}</ThemeContext>;
}React 19's use(Context)
React 19 can also read context with use(ThemeContext). Unlike useContext, use may be called inside an if statement. For ordinary cases useContext is all you need.
In real projects
Where this shows up in real projects
Context is most common for data that nearly the whole app needs and that changes rarely: the light/dark theme, the UI language (Myanmar/English on this very site), the signed-in user and their permissions, feature flags. Libraries use context under the hood too: React Router passes the current location, TanStack Query its QueryClient, and UI libraries their theme. That is why you often see many providers stacked near an app's root.
Most teams put each context in its own file and export a provider component together with a custom Hook such as useTheme(). Components call the Hook instead of touching the context object, which makes it easy to change the implementation later. Fast-changing state needed by only a few components, like an input's value, stays out of context, because every change would re-render all of its consumers.
Common mistakes
Common mistakes
1. Placing the provider below or beside the consumer
If a component calls useContext and renders the provider in its own return, it does not see that provider's value; it gets whatever is above it, usually the default. The provider must be above the consumer, on the parent side. When you only ever see the default, check this first.
2. Passing a new object as the value on every render
<UserContext value={{ user, logout }}> is a new object on every provider render, so all consumers re-render even when user did not change. Small apps will not notice, but with many consumers, keep the object stable with useMemo.
3. Reaching for context to skip just two levels
Context hides where data comes from, which can make components harder to reuse and test. For a level or two, pass props, or first consider composition, passing the element through children: <Layout><UserMenu user={user} /></Layout>.
Best practices
Best practices
- Give each context one meaning, such as ThemeContext or AuthContext, rather than piling all app data into one big context, because changing any part re-renders every consumer.
- For contexts that make no sense without a provider, default to null and throw a clear error in the custom Hook, so a forgotten provider is noticed immediately.
- Place a provider close to the subtree that needs it; a context used by one screen does not belong at the app root.
- In tests, wrap the component in a provider and pass different values to check each theme or language.
Mini challenge
Mini challenge: a language context
Write a LanguageProvider that switches between English and Myanmar, a useLanguage Hook, and two components that use it. One section must override the language with its own provider.
- A pure translate(lang, key) returns the text from MESSAGES, or the key itself when it is missing
- LanguageProvider owns lang state starting from an initial prop and provides { lang, toggle }
- Use createContext(null), and make useLanguage() throw when there is no provider
- App shows a Greeting and a switch button in an English provider, plus a Greeting in an initial="my" provider
import { createContext, useContext, useState } from 'react';
const MESSAGES = {
en: { greeting: 'Hello', switch: 'Switch language' },
my: { greeting: 'မင်္ဂလာပါ', switch: 'ဘာသာပြောင်းရန်' },
};
export function translate(lang, key) {
// TODO: look up MESSAGES[lang][key], fall back to key
}
// TODO: LanguageContext with null as the default
function LanguageProvider({ initial = 'en', children }) {
// TODO: lang state + toggle between 'en' and 'my'; provide both
}
export function useLanguage() {
// TODO: read the context; throw a helpful error when it is null
}
// TODO: Greeting({ name }) and SwitchButton() using useLanguage()
export default function App() {
// TODO: outer English provider, inner provider with initial="my"
}Expected: First render: Hello, Aye! / Switch language button / မင်္ဂလာပါ, Ko Ko! After clicking the switch button: မင်္ဂလာပါ, Aye! / ဘာသာပြောင်းရန် button / မင်္ဂလာပါ, Ko Ko! (the inner one is unchanged) Rendering Greeting without a provider throws useLanguage's error.
Show hint
In translate, use optional chaining and ??: MESSAGES[lang]?.[key] ?? key. The inner provider has its own state, so the outer switch button does not change the inner Greeting.
Show solution
import { createContext, useContext, useState } from 'react';
const MESSAGES = {
en: { greeting: 'Hello', switch: 'Switch language' },
my: { greeting: 'မင်္ဂလာပါ', switch: 'ဘာသာပြောင်းရန်' },
};
export function translate(lang, key) {
return MESSAGES[lang]?.[key] ?? key;
}
const LanguageContext = createContext(null);
function LanguageProvider({ initial = 'en', children }) {
const [lang, setLang] = useState(initial);
const toggle = () => setLang((l) => (l === 'en' ? 'my' : 'en'));
return <LanguageContext value={{ lang, toggle }}>{children}</LanguageContext>;
}
export function useLanguage() {
const context = useContext(LanguageContext);
if (context === null) {
throw new Error('useLanguage must be used inside <LanguageProvider>');
}
return context;
}
export function Greeting({ name }) {
const { lang } = useLanguage();
return <p>{translate(lang, 'greeting')}, {name}!</p>;
}
function SwitchButton() {
const { lang, toggle } = useLanguage();
return <button type="button" onClick={toggle}>{translate(lang, 'switch')}</button>;
}
export default function App() {
return (
<LanguageProvider>
<Greeting name="Aye" />
<SwitchButton />
<LanguageProvider initial="my">
<Greeting name="Ko Ko" />
</LanguageProvider>
</LanguageProvider>
);
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Context delivers a value to a whole subtree without drilling props: createContext → <Ctx value> → useContext.
- React 19 lets you write <Ctx value>; <Ctx.Provider value> still works.
- useContext takes the nearest provider and falls back to the default only when there is none.
- Keep state in the provider and expose it through a custom Hook to make context updatable, and keep fast-changing local data out of it.
React Documentation — React