context
useContext
Reads the current value of a React context from the nearest matching Provider above in the tree. Reach for it to share values like themes, auth, or locale without prop-drilling through every intermediate component.
const value = useContext(SomeContext) Parameters & Behavior
| Parameter | Purpose |
|---|---|
| SomeContext | The context object created with createContext(defaultValue) |
| return value | The value from the nearest <SomeContext.Provider value=...>, or the default |
| re-render trigger | Consumer re-renders whenever the Provider's value changes (Object.is) |
| no selector | There is no built-in way to subscribe to a slice — split contexts or memoize |
Examples
const ThemeContext = createContext('light');
function Button() {
const theme = useContext(ThemeContext);
return <button className={theme}>OK</button>;
} Read a theme value passed by an ancestor Provider
<AuthContext.Provider value={{ user, logout }}>
<App />
</AuthContext.Provider> Providing an auth object — memoize the value to avoid needless re-renders
const value = useMemo(() => ({ user, logout }), [user]);
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>; Stable object identity prevents every consumer from re-rendering on parent renders
const locale = useContext(LocaleContext);
return <p>{t('hello', locale)}</p>; Pulling a locale down without threading props
Gotcha
Every consumer re-renders on any Provider value change — pass a stable, memoized value. Splitting one large context into several narrow ones is usually simpler than a custom selector.
Related hooks
useReducer
Manages component state through a reducer function that maps (state, action) to the next state. Reach for it when state transitions are complex, involve multiple sub-values, or when the next state depends on the previous in non-trivial ways.
useMemo
Memoizes the result of a computation between renders, recomputing only when a dependency changes. Reach for it when a calculation is genuinely expensive or when you need a stable reference (e.g. as a dep of another hook or a context value).
useSyncExternalStore
Subscribes a component to an external store in a way that is safe with concurrent rendering, preventing tearing. Reach for it when writing a library or reading from a store that lives outside React (Redux, Zustand, browser APIs, custom event emitters).
useId
Generates a unique, stable string ID that is consistent between server and client renders. Reach for it whenever you need to associate elements (label htmlFor, aria-describedby) without collisions in an SSR-safe way.