HomeReact
Chapter 10

10 — useContext & Context API

The Context API lets you share data across the component tree without passing props through every level (avoids "prop drilling").

When to Use Context

✅ Good Use Cases❌ Bad Use Cases
Theme (light/dark)Frequently changing data (use state manager)
Auth (current user)Data used by only 1-2 levels deep (just pass props)
Locale / languageEvery piece of state in your app
Feature flagsHigh-frequency updates (causes re-renders)

Context Pattern

// 1. Create context with default value
const ThemeContext = createContext<Theme>("light");
 
// 2. Provide value at the top of the tree
<ThemeContext.Provider value={theme}>
  <App />
</ThemeContext.Provider>
 
// 3. Consume in any child
const theme = useContext(ThemeContext);

Performance Caveat

Every component that calls useContext(SomeContext) re-renders when the context value changes. Mitigations:

  • Split contexts (separate theme from auth)
  • Memoize the value object
  • Use React.memo on children
  • Consider Zustand/Jotai for high-frequency updates

File

  • context.tsx — theme context, auth context, multi-context, performance patterns, context + useReducer