React Reference ยท State Hooks
React useContext hook
Reference for React useContext: read the value of the nearest context provider, understand default values, re-render rules and the React 19 provider syntax.
useContext reads a value that a component higher in the tree made available with a context provider. It lets you pass data (a theme, the signed-in user, a locale) to deeply nested components without threading it through every level of props.
You create a context object with createContext(defaultValue), wrap part of the tree in <Context value={...}>, and call useContext(Context) in any component below it. The component re-renders whenever the provided value changes.
const ThemeContext = createContext('light'); function Button() { const theme = useContext(ThemeContext); return <button className={theme}>OK</button>; }
Try it
The first Label has no provider above it, so it receives the default value light; the one inside App follows the state.
Syntax
const value = useContext(SomeContext);
function useContext<T>(context: React.Context<T>): T; function createContext<T>(defaultValue: T): React.Context<T>;
| Name | Description |
|---|---|
SomeContext |
A context object created by createContext. Not the provider, and not a value. |
Returns: the value prop of the closest <SomeContext value> above the calling component. If there is none, the defaultValue given to createContext.
Edge cases: the default value is only used when no provider exists; a provider with value={undefined} supplies undefined. useContext must be called at the top level of a component or hook, never conditionally. If you need to read context after an early return or inside a condition, use use(Context).
Usage notes
- Provider syntax: React 19 lets you render
<ThemeContext value={...}>directly. Older code writes<ThemeContext.Provider value={...}>, which still works. - Re-render rule: when the provided value changes (compared with
Object.is), every component that reads that context re-renders, even if it ignores the changed part. Intermediate components wrapped inmemoare skipped unless they read the context. - Unstable values:
value={{ a, b }}creates a new object on every render of the provider and re-renders all consumers each time. Memoize withuseMemowhen the provider re-renders often, or split into separate contexts. - Updates need state. Context only distributes a value. To change it, provide a setter or
dispatchnext to the value, usually fromuseStateoruseReducer. - Nearest wins. Providers can be nested; each consumer sees the closest one.
- Default values are useful for isolated tests and Storybook, but a missing provider in the app is often a bug. A custom hook that throws (as above) makes the mistake obvious.
- Not a global store. For rapidly changing data read by many components, an external store with
useSyncExternalStoreusually performs better.
Related
- use, useReducer, useSyncExternalStore
- Lessons: Context, Context patterns