React · Chapter 15 of 42

useContext Hook

Context lets you share data (like theme or logged-in user) across a component tree without manually passing props at every level — avoiding 'prop drilling'.

`useContext` reads the current value of a Context inside a function component.

Creating context

Use `createContext(defaultValue)` to create a Context object, then wrap components with `<MyContext.Provider value={...}>` to supply a value.

Consuming context

Call `useContext(MyContext)` inside any descendant component to read the current value directly, no matter how deeply nested.

Example 1 (jsx)
import { createContext, useContext } from "react";

const ThemeContext = createContext("light");

function ThemedButton() {
  const theme = useContext(ThemeContext);
  return <button>Theme: {theme}</button>;
}

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <ThemedButton />
    </ThemeContext.Provider>
  );
}
Output
Theme: dark

ThemedButton reads 'dark' from context without receiving it as a prop.

Key points

  • Context avoids passing props through many intermediate components.
  • createContext() creates a Context object with a default value.
  • A Provider component supplies the actual value to descendants.
  • useContext(MyContext) reads the current context value.
💡 Note: Overusing context for frequently changing values can cause unnecessary re-renders — use it for stable, app-wide data.

📝 Quick Quiz

1. What problem does Context solve?

2. What component supplies a context value?

3. Which hook reads a context's current value?