0
React · Advanced React
New technique
Context: skip the prop chain
Some things the whole app needs to know, like the theme or who's logged in. Context makes them available to every component below.
Remember prop drilling: passing a value through layers that don't use it? Context lets a parent offer a value to every component below it, at any depth, without threading it through the props of each layer. It's made for app-wide things such as the theme, the logged-in user or the language.
const ThemeContext = createContext("dark");
const App = () => {
return (
<ThemeContext value="light">
<Toolbar />
</ThemeContext>
);
};
const Toolbar = () => {
const theme = useContext(ThemeContext);
return <p>Theme: {theme}</p>;
};createContext(default)creates a context.<ThemeContext value={…}>provides a value to everything inside it (React 19). Older code writes<ThemeContext.Provider value={…}>.useContext(ThemeContext)reads the value from the nearest provider above. No provider? You get the default.- Providers can be nested; an inner one overrides the outer one for its subtree.