React’s useContext hook simplifies global state management by allowing components to share data without passing props down the component tree
Example
// 1. Create a context
const ThemeContext = React.createContext();
function App() {
const [theme, setTheme] = React.useState('light');
return (
// 2. Provide the theme value to descendants
<ThemeContext.Provider value={{ theme, setTheme }}>
<Header />
<ToggleThemeButton />
</ThemeContext.Provider>
);
}
function Header() {
const { theme } = useContext(ThemeContext); // 3. Consume the context
return <h1>Current Theme: {theme}</h1>;
}
function ToggleThemeButton() {
const { theme, setTheme } = useContext(ThemeContext);
return (
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Toggle Theme
</button>
);
}
In this example:
- The theme is stored in the ThemeContext and provided via the Provider.
- The useContext hook allows Header and ToggleThemeButton components to access and modify the theme without passing props.
Advantages of useContext
- Prop Drilling Elimination: You avoid passing props through multiple layers of components.
- Centralized State: Ideal for global states like themes, authentication, or user preferences.
- Cleaner Code: Fewer intermediary props simplify component relationships.
Conclusion
useContext streamlines sharing and managing global state across React components, offering a clean alternative to complex prop chains. For larger applications requiring more advanced state management, pairing useContext with tools like Redux or useReducer may be ideal.