useContext: Sharing Data Without Props
Passing the same prop through many levels ("prop drilling") gets messy. Context lets any component deep in the tree read a value directly. It is good for the theme, the language and the logged-in user.
Context is like a radio broadcast inside your app: a provider at the top broadcasts a value, and any component below can tune in, no matter how deep. It's ideal for values many components need - the logged-in user, the theme, the language, the cart. For data only one or two components use, normal props are simpler and clearer.
Example
<!DOCTYPE html>
<html>
<head></head>
<body>
<div id="root"></div>
<script src="https://unpkg.com/react@18.3.1/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@18.3.1/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone@7.24.7/babel.min.js"></script>
<script type="text/babel">
const { createContext, useContext, useState } = React;
const ThemeContext = createContext("light");
function Button({ children }) {
const theme = useContext(ThemeContext); // read the nearest value
const style = theme === "dark"
? { background: "#111", color: "#fff" }
: { background: "#eee", color: "#111" };
return <button style={{ ...style, padding: 8, border: 0, borderRadius: 6 }}>{children}</button>;
}
function Toolbar() {
return <div><Button>Save</Button> <Button>Share</Button></div>; // no theme prop needed
}
function App() {
const [theme, setTheme] = useState("light");
return (
<ThemeContext.Provider value={theme}>
<Toolbar />
<p>
<button onClick={() => setTheme(t => (t === "light" ? "dark" : "light"))}>
Switch to {theme === "light" ? "dark" : "light"}
</button>
</p>
</ThemeContext.Provider>
);
}
ReactDOM.createRoot(document.getElementById("root")).render(<App />);
</script>
</body>
</html>▶ Try it yourselfThree steps
createContext(defaultValue)- make the context.<MyContext.Provider value={...}>- wrap the part of the app that can read it.useContext(MyContext)- read it in any child.
Every component reading a context re-renders when its value changes. Keep contexts small and focused (one for theme, one for user) rather than one giant context.
Key points
- Context shares values without passing props through every level.
- createContext, a Provider with a value, and useContext to read it.
- Keep contexts small and focused.
📝 Test yourself
1. What problem does context solve?
2. Which component supplies the value?
3. Fill in the hook that reads a context:
const theme = (ThemeContext);
