Hooks Essentials

React useContext Hook

Share data across component trees without prop drilling using context and useContext.

When to use context

Use context for cross-cutting app concerns:

  • Auth/session
  • Theme
  • Locale
  • Feature flags

Create and provide context

tsx
const ThemeContext = createContext<'light' | 'dark'>('light');

function Root() {
  return (
    <ThemeContext.Provider value="dark">
      <App />
    </ThemeContext.Provider>
  );
}

Consume context

tsx
function Header() {
  const theme = useContext(ThemeContext);
  return <header data-theme={theme}>Header</header>;
}

Best practices

  • Keep context value stable when possible
  • Split unrelated contexts
  • Wrap access in custom hooks for cleaner APIs

Next, we will learn useRef.