0
State Management · Context & Providers
New technique
Context: a notice on the forge wall
Instead of whispering the news to every smith in turn, pin it on the wall. Anyone below can read it.
Context lets a component make a value available to every component below it, however deep, without passing props through each layer.
It takes three pieces: you create a context once (usually in its own file, exported), a component high up provides a value, and any component below reads it. The components in between don't know or care.
const ThemeContext = createContext("light");
const App = () => {
return (
<ThemeContext value="dark">
<Page />
</ThemeContext>
);
};
const Button = () => {
const theme = useContext(ThemeContext);
return <button className={theme}>Forge</button>;
};createContext(default)defines the context and its default value.<ThemeContext value={…}>provides a value to its subtree (React 19). Older code writes<ThemeContext.Provider value={…}>. The prop must be calledvalue: a provider ignores every other prop.useContext(ThemeContext)reads the value in any component below.