React Reference ยท Top-Level React APIs
React createContext() function
Reference for React createContext: create a context object with a default value, provide it with a Provider, read it with useContext, and avoid common pitfalls.
createContext creates a context: a channel that lets a component pass a value to everything below it in the tree without threading it through every props list. You call it once, outside any component, and get back a context object. Components below a provider read the value with useContext (or use).
The function itself holds no changing data. It only creates the channel and remembers a default value. The actual value comes from a provider rendered higher in the tree.
import { createContext } from 'react'; const ThemeContext = createContext('light');
Try it
Syntax
function createContext<T>(defaultValue: T): Context<T>;
| Name | Description |
|---|---|
defaultValue |
The value a component receives when there is no provider above it. It is never used when a provider exists, even if the provider's value is undefined. Pick a value that makes sense on its own, or null to signal "missing provider". |
Returns: a context object. In React 19 the context object itself can be rendered as a provider (<ThemeContext value={...}>). The older ThemeContext.Provider and ThemeContext.Consumer properties still exist; see Context.Provider and the context as a provider.
The object also has an optional displayName property that React DevTools uses as the label.
Usage notes
- Create the context at module level, never inside a component. A context created during render would be a new channel on every render, and consumers would never match their provider.
- The default value is a fallback, not an initial state. It is useful for tests and for components that can work without a provider. It does not change over time.
- Consumers re-render when the provider's value changes, compared with
Object.is. Passing a fresh object such asvalue={{ count, setCount }}re-renders every consumer whenever the provider re-renders. Wrap such objects inuseMemowhen the provider re-renders often for other reasons. - The nearest provider wins. Providers can be nested to override a value for one subtree, as the first example shows.
- Wrap the context in a custom hook (like
useCounterabove). It hides the context object, gives one place to check for a missing provider, and lets you change the implementation later. - Do not put everything in one context. Split unrelated values (theme, user, settings) so a change in one does not re-render consumers of the others.
- Context is not a state manager. It only distributes a value. The state itself still lives in
useState,useReduceror an external store. - Version note: using
<Context value>as a provider is new in React 19. In React 18 and earlier you must write<Context.Provider value>.