How to Use the useContext Hook in React
Sharing values across components without passing props down.
When building React apps you'll sometimes have a value that a lot of components
need, like the current theme or the signed-in user. Passing it down as a prop
through every component in between, often called prop drilling, gets tedious
very quickly. Context lets you skip the middle, and the useContext hook makes reading
it simple.
Context lets a parent component make a value available to every component below it, no matter how deep.
Step 1: Create the Context
Create a context with React.createContext. The argument is the defualt value,
used when there's no provider above a component:
// ThemeContext.jsimport React from "react"export const ThemeContext = React.createContext("light")
Step 2: Provide a Value
Wrap part of your app in the context's Provider and pass it a value. Here
the theme is kept in useState, so clicking the button updates it:
// App.jsimport React, { useState } from "react"import { ThemeContext } from "./ThemeContext"import Toolbar from "./Toolbar"function App() {const [theme, setTheme] = useState("light")return (<ThemeContext.Provider value={theme}><Toolbar /><button onClick={() => setTheme(theme === "light" ? "dark" : "light")}>Toggle theme</button></ThemeContext.Provider>)}
Step 3: Read It with useContext
Any component inside the provider can read the value with useContext:
// ThemedButton.jsimport React, { useContext } from "react"import { ThemeContext } from "./ThemeContext"function ThemedButton() {const theme = useContext(ThemeContext)return <button className={`button-${theme}`}>Current theme: {theme}</button>}
Toolbar can render ThemedButton without knowing anything about the theme.
When the theme changes, every component that calls useContext(ThemeContext)
re-renders with the new value.
Updating the Value from a Child
To let a child change the value, pass the setter along with it in an object:
<ThemeContext.Provider value={{ theme, setTheme }}><Toolbar /></ThemeContext.Provider>
Then destructure both out of the context:
function ThemeToggle() {const { theme, setTheme } = useContext(ThemeContext)return (<button onClick={() => setTheme(theme === "light" ? "dark" : "light")}>Switch to {theme === "light" ? "dark" : "light"} mode</button>)}
When to Use Context
Context works best for values a lot of your app needs: the theme, the current user or the language. If a value only goes down one or two levels, plain props are simpler and easier to follow.
Have some feedback on this post? .