Passing a prop down through many layers just to reach a deep component — prop drilling — is tedious and fragile. React Context lets you provide a value at the top of the tree and read it anywhere below, no matter how deep. It's how themes, the current user and app settings are shared.
The prop-drilling problem
If App has the current user and a button five levels down needs it, you'd thread user through every component in between — even ones that don't use it. Context removes that plumbing.
Creating context
import { createContext, useContext, useState } from "react";const ThemeContext = createContext(null);export function ThemeProvider({ children }) {const [theme, setTheme] = useState("light");const value = { theme, toggle: () => setTheme(t => t === "light" ? "dark" : "light") };return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;}
Consuming context
Wrap the app in the provider, then any descendant reads the value with useContext — often via a small custom hook for convenience:
// A convenience hookexport const useTheme = () => useContext(ThemeContext);// Any component, any depth:function ThemeToggle() {const { theme, toggle } = useTheme();return <button onClick={toggle}>Theme: {theme}</button>;}
Context + reducer
For real global state, combine Context (to share) with useReducer (to manage) — a lightweight alternative to a state library for many apps:
function AppProvider({ children }) {const [state, dispatch] = useReducer(reducer, initial);return (<AppContext.Provider value={{ state, dispatch }}>{children}</AppContext.Provider>);}
When (not) to use it
Practice
Build a ThemeProvider with a useTheme hook and a toggle button that works no matter how deeply nested. Then add an AuthContext holding a fake user and a logout, and read it from a header component.
Key takeaways
- 01Context shares a value across the tree without prop drilling.
- 02createContext + a Provider supply the value; useContext reads it anywhere below.
- 03Wrap useContext in a small custom hook (useTheme) for ergonomics.
- 04Context + useReducer is a lightweight global-state pattern.
- 05Every consumer re-renders on value change — use Context for stable app-wide data, a library for heavy state.
