What problem does the Context API solve in React?
Short answer
Context lets you share a value, such as the current logged in user or a color theme, with many components at once, without needing to manually pass it down as a prop through every single component in between.
Advertisement
AModel answer
Context lets you share a value, such as the current logged in user or a color theme, with many components at once, without needing to manually pass it down as a prop through every single component in between.
const ThemeContext = React.createContext('light');
function App() {
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
function Toolbar() {
const theme = useContext(ThemeContext);
return <div className={theme}>Toolbar</div>;
}Real-world example
A large app shares the current signed in user's information with many different components scattered across the page, without having to pass that user object through every single component in between.
Likely follow-ups
- What happens to a component that uses useContext if there is no matching Provider above it?
- How is Context different from a global JavaScript variable?
Related topics