DevPath · Learn to code ESPTEN

useReducer and Context

Context API: avoiding prop drilling

The problem: prop drilling

Imagine that a piece of data (the user, the theme, the language) is needed by a very deep component in the tree. Without more tools, you have to pass it through props across all the intermediate components, even if they don't use it. This is called "prop drilling": props that are only passing through, cluttering signatures and coupling components that should not know about that data.

The solution: Context

The Context API lets a distant component read a value without passing it through props at each level. It has three pieces:

1. Create the context

const ThemeContext = React.createContext("light");

The argument is the default value (used if there is no Provider above).

2. Provide a value with <Ctx.Provider>

Wrap the part of the tree that should have access to the value:

<ThemeContext.Provider value="dark">
  <Page />
</ThemeContext.Provider>

Everything inside will be able to read that value, no matter how deep it is.

3. Read the value with useContext

Any descendant component reads it with the useContext hook:

function Button() {
  const theme = useContext(ThemeContext);
  return <button className={theme}>Current theme: {theme}</button>;
}

Without context, theme would have had to travel through props along the whole chain. With context, the component consumes it directly from the nearest Provider.

React.createContext and useContext are already available in the exercises.

Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
← useReducer: state with clear transitionsLifting state up →