Hook · Context
useContext
Skip prop drilling
useContext reads a value published by the nearest Provider up the tree. It's the way to share theme, locale, session, or any cross-cutting dependency without passing it through every component.
Three pieces
createContext(default) creates the channel. A <Ctx.Provider value=...> publishes a value. useContext(Ctx) reads it in any descendant.
Costs to keep in mind
When the value changes, all consumers re-render. If your value is { user, setUser } created inline, it changes on every render. Memoize the value or split it into multiple contexts.
Common pitfalls
- 01Passing a new object as value on every render causes all consumers to re-render. Memoize the value with useMemo.
- 02Context is not a state manager: it has no built-in optimization. Split contexts by update frequency.
- 03A missing Provider makes useContext return the default value — make the default as safe as possible.
Was this helpful?
Sign in to give feedback
