Avoid prop drilling
A deeply nested component needs shared theme, locale, or display settings without receiving them through every intermediate component.
React 19+ · Function
createContext creates a context object with a static fallback value. Providers supply values to descendants, which can read the nearest value with useContext.
Call createContext outside components to define a context object and its static fallback. A provider supplies a value to descendants, while useContext reads the nearest matching value; without a provider, consumers receive the fallback.
createContext(defaultValue)| Name | Type | Description |
|---|---|---|
defaultValue | any | The static fallback value used when no matching provider exists above a component reading the context. Use null when no meaningful fallback exists. |
A context object representing the context that components can provide or read.
import { createContext, useContext } from 'react';
const ThemeContext = createContext('light');
function Label() {
const theme = useContext(ThemeContext);
return <span data-theme={theme}>Current theme: {theme}</span>;
}
export default function App() {
return (
<ThemeContext value="dark">
<Label />
</ThemeContext>
);
}Creates a module-level context with a fallback and provides a different value to a descendant.
A deeply nested component needs shared theme, locale, or display settings without receiving them through every intermediate component.
Several descendants need access to one application-level value such as the current user or feature configuration.
A component tree needs a safe value when rendered outside its normal provider.
createContext defines a context object and accepts one defaultValue. That value is returned to a consumer when no matching provider exists above it; otherwise the consumer reads the provider's value.
Follow-up: What does the context object store? It does not store the current data; it identifies the context type used by providers and consumers.
Create the context at module scope, then provide a value from an ancestor and read it with useContext in descendants. This avoids threading the same data through every intermediate component as props.
Follow-up: How can a component receive a value without a provider? useContext returns the static defaultValue supplied when the context was created.
The provider determines the value visible to descendants, while createContext supplies the fallback for an unprovided tree. In React 19, the context can be rendered directly with a value prop, as in <ThemeContext value="dark">.
Follow-up: What should be passed when there is no sensible fallback? Use null, then handle that absence explicitly in consumers.
useContextuseContextProvider