Sub topic 2
Creating a context
This chapter assumes you know JavaScript modules and destructuring, React function components, JSX and props, and the useState hook. You also need a basic idea of when React re-renders a component. By the end, you will be able to create a context object, decide where it lives in your project, and avoid the mistakes that come with creating one.
What createContext does
In the previous chapter you saw prop drilling. A value such as the current theme gets passed through many components that never use it. Context avoids this by giving the value a separate channel through the tree.
The first step is to create that channel. You do it with createContext, a function exported by react.
import { createContext } from 'react';
export const ThemeContext = createContext('light');createContext takes one argument, the default value. It returns a context object. That object does not hold your application's current state. It is an identity: a unique key that a provider and a consumer both refer to so React can match them.
Think of a context as a named slot in the tree. Creating it only declares that the slot exists. Two other steps fill the slot and read from it, and later chapters cover them:
- A
Providerplaces a value in the slot for everything rendered inside it. useContextreads the value from the nearest provider above the calling component.
What the returned object contains
The context object has a few properties you will meet:
| Property | Purpose |
|---|---|
| `Provider` | A component that supplies a value to its subtree. |
| `Consumer` | An older component that reads the value through a render function. Most code now uses `useContext` instead. |
| `displayName` | An optional string that React DevTools shows for the context. |
In React 19 and later, you can also render the context object itself as the provider, writing <ThemeContext value={theme}> instead of <ThemeContext.Provider value={theme}>. The .Provider form works in every React version that has hooks, so this tutorial uses it.
You should never read or write the object's internal fields. Treat it as an opaque handle that you pass to Provider and useContext.
Where to create a context
Call createContext once, at module scope, and export the result. Do not call it inside a component.
import { createContext, useContext, useState } from 'react';
// Wrong: a new context object is created on every render.
function BrokenApp() {
const ThemeContext = createContext('light');
const [theme] = useState('dark');
return (
<ThemeContext.Provider value={theme}>
<Child />
</ThemeContext.Provider>
);
}
function Child() {
// This component has no access to the context created inside BrokenApp.
return <p>Cannot read the context here</p>;
}There are two problems with this. First, Child cannot import a context that exists only inside a function body. Second, even if you passed it down some other way, each render would produce a different context object. React would see an unrelated slot every time, and consumers would never match their provider.
The correct pattern puts the context in its own module:
// ThemeContext.js
import { createContext } from 'react';
export const ThemeContext = createContext('light');// ThemedButton.js
import { useContext } from 'react';
import { ThemeContext } from './ThemeContext.js';
export function ThemedButton() {
const theme = useContext(ThemeContext);
return <button className={`btn-${theme}`}>Save</button>;
}// App.js
import { useState } from 'react';
import { ThemeContext } from './ThemeContext.js';
import { ThemedButton } from './ThemedButton.js';
export default function App() {
const [theme, setTheme] = useState('dark');
return (
<ThemeContext.Provider value={theme}>
<ThemedButton />
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Toggle theme
</button>
</ThemeContext.Provider>
);
}Both App.js and ThemedButton.js import the same object from ThemeContext.js. JavaScript modules are evaluated once, so every importer receives the identical object. That shared identity is what lets React connect the provider to the consumer.
Why a separate file
Putting each context in its own file, or in a small group of related files, has practical benefits:
- Providers and consumers can import it without importing each other, which avoids circular imports.
- There is exactly one place to change the default value or the
displayName. - Tools that hot-reload components work better when a file exports either components or plain values, not a mix.
For small apps, a single contexts.js file that exports several contexts is also fine. Pick one convention and keep to it.
Choosing the default value
The argument you pass to createContext is used only when a component calls useContext and has no matching provider above it in the tree. It is not the initial state of anything. It does not change when state changes. A later chapter covers it in detail, but you must make a choice when you write the call, so here are the common options.
- A real fallback.
createContext('light')works when the context has a sensible standalone value. Components can render correctly without any provider. null.createContext(null)works when a missing provider is a programming mistake. A custom hook can check fornulland throw a clear error. You will build that hook in a later chapter.- A full default object. Use this when you want the shape documented in one place, for example
createContext({ user: null, login: () => {}, logout: () => {} }). Be careful with this one. Silent no-op functions can hide a missing provider, and your app will seem to work while doing nothing.
undefined is a poor default. A component that reads the context without a provider gets undefined, which looks the same as a value that was never set. Use null as an explicit "no value" marker instead.
Naming and displayName
By convention, a context is named in PascalCase and ends with Context, such as ThemeContext or AuthContext. The name matters when you read your own code, and it matters in React DevTools. DevTools shows a context's displayName if one is set. Without it, every context appears as Context.Provider, which makes debugging harder when you have several.
import { createContext } from 'react';
export const AuthContext = createContext(null);
AuthContext.displayName = 'AuthContext';Setting displayName has no effect on behavior. It is a debugging aid only. It is most useful once an app has more than two or three contexts.
One context or many
Each createContext call makes an independent slot. Nothing links two contexts together, even if they hold related data. This matters for two reasons.
First, you can have as many contexts as you need, and each one can have its own provider placed wherever it should apply. A theme can wrap the whole app while an editor's settings wrap one screen.
Second, a component that reads a context re-renders when that context's value changes. If you put unrelated data into one context, components that care about only part of it still re-render on any change. A later chapter covers splitting contexts for that reason. For now, a good rule is to create one context per concern, such as theme, current user or locale, and avoid a single "app state" context that holds everything.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Consumers always show the default value | No provider above them, or the provider imports a different context object | Check that provider and consumer import from the same module path |
| Two contexts that should be the same behave independently | The context file is imported under two different paths, or the package is duplicated in a bundle | Use one import path and one copy of the module |
| `ThemeContext.Provider` is `undefined` | The import was wrong, such as a default import for a named export | Match `export const` with `import { ... }` |
| Consumers never update | `createContext` is called inside a component | Move the call to module scope |
| DevTools lists several nameless `Context.Provider` entries | `displayName` was never set | Set `displayName` on each context |
Summary
createContext(defaultValue) returns a context object that works as a shared key. Create it once at module scope, export it, and import the same object everywhere a provider or consumer needs it. Choose the default value deliberately, and name each context so it is easy to find in DevTools. Creating a context does not store any state. The provider supplies the value, and useContext reads it.
Exercise
A teammate writes const LocaleContext = createContext('en'); inside the body of a Settings component and exports nothing. They then ask why a Footer component, in another file, always shows nothing from the context. Name two things wrong with this code and show the corrected file layout.
Show answer
The context is created inside a component, so a new context object is made on every render, and it is not exported, so Footer has no way to import it. Move the call to module scope in its own file and export it: in LocaleContext.js, write import { createContext } from 'react'; export const LocaleContext = createContext('en');. Then import LocaleContext in both the component that renders LocaleContext.Provider and in Footer, so both refer to the same object.
Exercise
You call useContext(AuthContext) in a component, and AuthContext was created with createContext(null). A provider above it renders <AuthContext.Provider value={undefined}>. What does the component receive, and why?
Show answer
It receives undefined. The default value null is used only when there is no provider above the component. A provider that is present always supplies its value prop, even when that value is undefined.