Capítulo 50 de 116

Chapter 50: useContext

Core Idea

useContext(SomeContext) reads and subscribes to the value of the nearest enclosing provider for that Context above the calling component — the read half of the Context mechanism introduced conceptually in Ch 32.

Key Concepts

  • Signature: const value = useContext(SomeContext) where SomeContext was created with createContext(defaultValue).
  • Resolution rule: React looks upward from the calling component and uses the value from the closest <SomeContext value={...}> provider — if there is none, it falls back to the defaultValue passed to createContext.
  • Automatic re-render on change: when the provider above re-renders with a different value, every descendant calling useContext(SomeContext) re-renders too, regardless of how many non-consuming components sit in between.
  • Providers can be overridden by nesting: a component wrapped in a second, nested provider for the same Context sees the inner (nearer) value — this is how a themed subsection can override an app-wide theme.
  • Passing an object as the value causes descendants to re-render on every parent render unless that object is itself memoized — a common performance pitfall when a Context value is { ...several fields } recreated fresh each render.
  • Calling useContext always subscribes — there's no way to read a Context value without also opting into re-rendering when it changes; if only occasional/on-demand reads are needed, that typically points toward passing a getter function through the Context value instead, or restructuring state.

Code Examples

const ThemeContext = createContext('light');

function Button() {
  const theme = useContext(ThemeContext); // nearest provider's value, or 'light'
  return <button className={theme}>Save</button>;
}
  • What it demonstrates: the read side of Context — no props were passed to Button for theme, yet it resolves correctly based on tree position.

Key Takeaways

  1. useContext always subscribes to future changes of that Context — there's no non-reactive "peek" variant.
  2. Memoize an object Context value (useMemo) if it's recreated on every provider render, or every consumer re-renders needlessly on unrelated provider re-renders.
  3. Multiple providers for the same Context nest correctly — always resolves to the nearest one above the reading component.

Connects To

  • Ch 32 (Passing Data Deeply with Context): the conceptual introduction this API reference completes.
  • Ch 80 (createContext): how the Context object consumed here is created.
  • Ch 33 (Scaling Up with Reducer and Context): useContext combined with useReducer for shared mutable state.