Skip to the workspace
Pebellslearn by building
State  ›  Capstone Project

useContext — Skipping the Middlemen

useContext 15 minContext lets a parent provide a value that any component below it can read with useContext, without passing it through every layer as props.

react / useContext — Skipping the Middlemen

Explore each scene at your own pace.

01 · The rule

The rule

useContext — Skipping the Middlemen

The reading list gets a dark theme. App holds the current theme, but the buttons that need it sit four components down. Passing theme through every layer — each one receiving it only to hand it on — is called prop drilling, and it makes every middle component care about data it never uses. Context lets a value skip the middlemen.

The rule

Provide it high, read it low, fall back to the default.

Three pieces, usually in three places:

// ThemeContext.js — create it, with a default
import { createContext } from 'react';
export const ThemeContext = createContext('light');
// App.jsx — provide it high
function App() {
  const [theme, setTheme] = useState('dark');
  return (
    <ThemeContext.Provider value={theme}>
      <ReadingList />
    </ThemeContext.Provider>
  );
}
// LikeButton.jsx — read it low
import { useContext } from 'react';
import { ThemeContext } from './ThemeContext';

function LikeButton() {
  const theme = useContext(ThemeContext);
  return <button className={`like like-${theme}`}>♥</button>;
}

In React 19 you can write <ThemeContext value={theme}> directly; .Provider still works and is what most existing code uses.

Provide it high. Everything inside the provider, at any depth, can read the value.

Read it low. useContext(ThemeContext) returns the value from the nearest provider above the component. When that value changes, every component reading it re-renders. Providers can nest: an inner provider overrides the outer one for its own subtree.

Fall back to the default. With no provider above it, useContext returns the default passed to createContext.

Context often carries state: put [theme, setTheme] or a dispatch from useReducer into the value, and any component below can both read and change it.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.