Sub topic 4
What the default value is for
This chapter assumes you can write function components with props and useState. You should also know that createContext, a Provider and useContext work together. This chapter covers one argument: the value you pass to createContext.
What the default value is
createContext(defaultValue) takes one argument. React stores it on the context object. A component that calls useContext(SomeContext) gets that value only when no matching provider exists above it in the tree.
import { createContext, useContext } from 'react';
const ThemeContext = createContext('light');
function Badge() {
const theme = useContext(ThemeContext);
return <span className={`badge badge-${theme}`}>{String(theme)}</span>;
}
export default function App() {
return (
<div>
<Badge />
<ThemeContext.Provider value="dark">
<Badge />
</ThemeContext.Provider>
<ThemeContext.Provider value={undefined}>
<Badge />
</ThemeContext.Provider>
</div>
);
}This renders three badges:
- The first has no provider above it, so it shows
light, the default. - The second sits under a provider with
value="dark", so it showsdark. - The third sits under a provider whose value is
undefined, so it showsundefined.
The third case surprises many people. The default is not a fallback for missing or undefined values. It applies only when React finds no provider at all. A provider that exists always wins, even if its value is undefined or null.
How React picks the value
When useContext runs, React looks at the nearest ancestor provider for that exact context object. If it finds one, it returns that provider's current value prop. If it reaches the root without finding one, it returns the default.
Two details follow from this lookup:
- The search matches the context object, not its name or shape. Two contexts created with identical defaults are unrelated.
- The default is chosen per call, based on where the component sits. The same component can see the default in one place and a provided value in another.
The following table summarizes the outcomes.
| Situation | Value returned by `useContext` |
|---|---|
| No provider above the component | The default passed to `createContext` |
| Provider with `value="dark"` above | `"dark"` |
| Provider with `value={undefined}` above | `undefined` |
| Provider with `value={null}` above | `null` |
| Provider with no `value` prop at all | `undefined` |
| Two nested providers | The value of the nearest one |
The fifth row is a common bug. Writing <ThemeContext.Provider> without a value prop gives consumers undefined, not the default.
The default never changes
The default is fixed when you call createContext. React does not re-read it or update it. No setter exists for it, and a component cannot change it. Anything that changes over time must come from a provider, usually backed by useState or useReducer.
This rules out a tempting but wrong pattern:
import { createContext, useContext } from 'react';
// Wrong: this default cannot hold changing state.
const CounterContext = createContext({ count: 0, increment: () => {} });
function CounterButton() {
const { count, increment } = useContext(CounterContext);
return <button onClick={increment}>Clicked {count} times</button>;
}
export default function App() {
// No provider: the button always shows 0 and clicking does nothing.
return <CounterButton />;
}The button renders, but increment is an empty function and count is always 0. Nothing throws an error, so the bug is silent. The code needs a provider that owns the state, as covered in the chapter on sharing changing state through context.
When a useful default makes sense
A default is most useful when the value is a static setting that components can reasonably read without any setup. These cases fit well:
- A theme or locale with a sensible baseline. A component library can default to
'light'or'en'so each component works out of the box. - Components used in isolation. Unit tests and tools such as Storybook often render one component with no providers. A realistic default lets that work without wrapper boilerplate.
- Configuration with a production fallback. For example, an API base URL or a feature flag set where "off" is the safe answer.
- Dependency injection with a real implementation. A context can hold a logger that defaults to
consoleand be replaced in tests.
import { createContext, useContext } from 'react';
const LoggerContext = createContext(console);
function SaveButton({ onSave }) {
const logger = useContext(LoggerContext);
return (
<button
onClick={() => {
logger.log('save clicked');
onSave();
}}
>
Save
</button>
);
}
export default function App() {
// No provider is needed. The default logger writes to the console.
return <SaveButton onSave={() => {}} />;
}A test can wrap SaveButton in <LoggerContext.Provider value={fakeLogger}> to capture calls, and production code never needs a provider.
When no sensible default exists
Some contexts have no meaningful standalone value. A logged-in user, a shopping cart, or a database connection exists only if something supplies it. A fake default there would hide mistakes: the component renders as if nothing were wrong, as in the counter example above.
For these contexts, use null as a sentinel meaning "no provider". Then check for it in a custom hook so a missing provider fails loudly:
import { createContext, useContext } from 'react';
const CartContext = createContext(null);
export function useCart() {
const cart = useContext(CartContext);
if (cart === null) {
throw new Error('useCart must be used inside <CartContext.Provider>');
}
return cart;
}
export { CartContext };This works only if no provider ever passes null as its value. If a provider can legitimately hold null, use a unique sentinel instead:
const NO_PROVIDER = Symbol('no provider');
const UserContext = createContext(NO_PROVIDER);The check becomes if (user === NO_PROVIDER) throw ..., and null stays available as real data such as "nobody is logged in".
Choosing between a default and a sentinel
Ask whether a component can do something correct without a provider.
| Question | If yes | If no |
|---|---|---|
| Is there a reasonable standalone behavior? | Use a real default | Use a `null` or `Symbol` sentinel |
| Does the value change over time? | Default is only the starting fallback; add a provider | Default alone may be enough |
| Would a missing provider be a programmer error? | Throw from a custom hook | Let the default apply |
| Do tests render components without wrappers? | A good default saves boilerplate | Provide a test wrapper |
Edge cases to remember
- Default objects are shared. The same default object is returned to every consumer outside a provider. Do not mutate it. Freeze it with
Object.freezeif it is an object. - Default and provider shapes must match. If the default is a string and the provider passes an object, consumers must handle both. Keep them the same type, or the code that reads the value will break in one of the two cases.
- Components under a provider never see the default. Moving a component into or out of a provider changes which value it receives. Reorganizing the tree can therefore change behavior without changing the component.
- The default does not trigger re-renders. It is constant, so nothing re-renders because of it. Re-render behavior is covered in a later chapter.
createContext()with no argument sets the default toundefined. That is legal and behaves like any other default, but a sentinel makes your intent clearer.
Exercise
A component calls useContext(LangContext), where LangContext = createContext('en'). It sits under <LangContext.Provider value={undefined}>. What does useContext return, and why?
Show answer
It returns undefined. The default 'en' is used only when no provider exists above the component. A provider is present here, so its value prop is returned, even though that value is undefined.
Exercise
You are building SessionContext for the signed-in user, and null already means "signed out". Write the context and a useSession hook that throws if the component is outside a provider, without confusing the two cases.
Show answer
Use a unique sentinel as the default so null stays available as real data:
const NOPROVIDER = Symbol('no provider');
const SessionContext = createContext(NOPROVIDER);
function useSession() {
const session = useContext(SessionContext);
if (session === NO_PROVIDER) {
throw new Error('useSession must be used inside <SessionContext.Provider>');
}
return session;
}
A provider passing value={null} then means "signed out", while a missing provider throws.