Context API — React

Context solves prop drilling, which is passing props through components that don't need them. There are three steps. First, write const ThemeContext =…

The dark theme picked in the top corner has to reach a button placed five component layers below it. With props, all five layers have to pass theme along, even though not one of them uses it.

Context gives you a shortcut: a value from a component near the top can be read by any component below it, without passing it through props at every layer. Think of the announcement speaker in a school. Instead of the principal handing a message to the homeroom teacher, the teacher to the class captain, and the captain to every student, the principal speaks once over the speaker. Anyone listening hears it right away. When the announcement changes, every listener hears the new version. In React, the principal is the component near the top that holds the value, the speaker is the context, and the students who listen are the components that read the context.

The problem: prop drilling

The ThemedButton and Footer components need theme. The value is kept in App, and it has to pass through Layout and Toolbar in between:

function App() {
  const [theme, setTheme] = useState("dark")
  return <Layout theme={theme} />
}

function Layout({ theme }) {
  return (
    <div>
      <Toolbar theme={theme} />
      <Footer theme={theme} />
    </div>
  )
}

function Toolbar({ theme }) {
  return (
    <nav>
      <ThemedButton theme={theme} />
    </nav>
  )
}

Layout and Toolbar don't use theme at all. They receive theme only to pass it down. Passing props through components that don't need them is called prop drilling. Two layers in between is fine. Ten layers means ten components to change every time there's new data.

Context in three steps

This is the same example, but using context. The numbers 1 to 3 in the code comments are the three steps:

import { createContext, useContext } from "react"

// 1. Make the context, with the default value "light"
const ThemeContext = createContext("light")

function App() {
  // 2. The Provider supplies a value to every component inside it
  return (
    <ThemeContext.Provider value="dark">
      <Layout />
    </ThemeContext.Provider>
  )
}

function Layout() {
  return (
    <div>
      <Toolbar />
      <Footer />
    </div>
  )
}

function Toolbar() {
  return (
    <nav>
      <ThemedButton />
    </nav>
  )
}

function ThemedButton() {
  // 3. Any component inside the Provider can read it
  const theme = useContext(ThemeContext)
  return <button className={theme}>Button {theme}</button>
}

function Footer() {
  const theme = useContext(ThemeContext)
  return <footer>Theme: {theme}</footer>
}

The result: a button reading Button dark, and a footer reading Theme: dark.

Forgot the Provider: the default value

You write createContext("light") but forget to add a Provider. Take a guess: does useContext(ThemeContext) give "light", undefined, or an error?

Above the component useContext(ThemeContext) gives
<ThemeContext.Provider value="dark"> "dark"
No Provider at all "light", the default from createContext

Without a Provider there's no error. useContext quietly gives the default value, "light". So pick a default that makes sense. If the theme in your app won't change, first check that the component really sits inside the Provider.

The value changes: who renders again

Usually the Provider's value comes from state, and the Provider is placed in a component of its own, here ThemeProvider:

function ThemeProvider({ children }) {
  const [theme, setTheme] = useState("dark")
  const toggle = () => setTheme(theme === "dark" ? "light" : "dark")

  return (
    <ThemeContext.Provider value={theme}>
      <button onClick={toggle}>Change theme</button>
      {children}
    </ThemeContext.Provider>
  )
}

function App() {
  return (
    <ThemeProvider>
      <Layout />
    </ThemeProvider>
  )
}

Click Change theme once, then count how many times each component has rendered (the first render counts too). The Prop drilling column is the version that passes theme through props:

Component Prop drilling Context
App 2 1
ThemeProvider (none) 2
Layout 2 1
Toolbar 2 1
ThemedButton 2 2
Footer 2 2

In the example above, the Change theme button is inside ThemeProvider. To place the button anywhere, for example inside Toolbar, share toggle through the context too:

const ThemeContext = createContext(null)

function ThemeProvider({ children }) {
  const [theme, setTheme] = useState("dark")
  const toggle = () => setTheme(theme === "dark" ? "light" : "dark")

  return (
    <ThemeContext.Provider value={{ theme, toggle }}>
      {children}
    </ThemeContext.Provider>
  )
}

function ThemeToggle() {
  const { theme, toggle } = useContext(ThemeContext)
  return <button onClick={toggle}>Theme: {theme}</button>
}

🎯 Context or props?

⚠️ When the context value doesn't arrive

TL;DR: Context solves prop drilling, which is passing props through components that don't need them. There are three steps. First, write const ThemeContext = createContext("light") outside every component. Second, wrap the components that need the value in <ThemeContext.Provider value="dark">. Third, read the value in any component inside with const theme = useContext(ThemeContext), then show {theme}. Without a Provider, useContext gives the default value ("light") with no error. When value changes, every component that calls useContext renders again. Use Context for global data (used in many places) that rarely changes. When the data only goes one or two component layers down, plain props are enough.

⚡ The problem: prop drilling

Meaning: Say the value theme (a dark or light theme) is kept in App, but the ones that need it are ThemedButton and Footer, further down. Layout and Toolbar sit in between, and receive theme only to pass it down. Passing props through components that don't need them is called prop drilling.

⚡ Context in three steps

Write:

// 1. Make the context, with the default value "light"
const ThemeContext = createContext("light")

function App() {
  // 2. The Provider supplies a value to every component inside it
  return (
    <ThemeContext.Provider value="dark">
      <Layout />
    </ThemeContext.Provider>
  )
}

function ThemedButton() {
  // 3. Any component inside the Provider can read it
  const theme = useContext(ThemeContext)
  return <button className={theme}>Button {theme}</button>
}

Meaning: Context lets any component below read a value from a component above, without props. Step 1: createContext("light") is written outside the components, and "light" is its default value. Step 2: the Provider wraps the components below it and supplies the value "dark". Step 3: useContext(ThemeContext) reads that value. Layout and Toolbar don't need to receive theme any more.

⚡ Forgot the Provider

Guess first: the context is made with createContext("light"), but you forgot to add a Provider. Does useContext(ThemeContext) give "light", undefined, or an error?

"light", the default from createContext("light"). There's no error, so pick a default that makes sense.

Meaning: One more thing about the Provider: once the Provider's value changes, every component that calls useContext(ThemeContext) renders again with the new value.

What you will learn