JAVASCRIPT
Global State Management with `useContext`
Avoid prop drilling and manage global application state efficiently across deeply nested components using React's `useContext` hook and the Context API.
import React, { createContext, useContext, useState } from 'react';
// 1. Create a Context
const ThemeContext = createContext(null);
// 2. Create a Provider Component
function ThemeProvider({ children }) {
const [theme, setTheme] = useState('light');
const toggleTheme = () => {
setTheme((prevTheme) => (prevTheme === 'light' ? 'dark' : 'light'));
};
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
{children}
</ThemeContext.Provider>
);
}
// 3. Create a Custom Hook to Consume the Context
function useTheme() {
const context = useContext(ThemeContext);
if (!context) {
throw new Error('useTheme must be used within a ThemeProvider');
}
return context;
}
// Example Component using the theme
function ThemedButton() {
const { theme, toggleTheme } = useTheme();
return (
<button
onClick={toggleTheme}
style={{
background: theme === 'light' ? '#fff' : '#333',
color: theme === 'light' ? '#333' : '#fff',
padding: '10px 20px',
border: 'none',
borderRadius: '5px',
cursor: 'pointer',
}}
>
Current theme: {theme}. Toggle theme.
</button>
);
}
// App structure
function App() {
return (
<ThemeProvider>
<div style={{ padding: '20px' }}>
<h1>Context API Example</h1>
<ThemedButton />
</div>
</ThemeProvider>
);
}
export default App;
How it works: The `useContext` hook, combined with `createContext` and a `Provider` component, enables efficient global state management. It allows components deeply nested in the tree to access context values without explicitly passing props down through every level, reducing 'prop drilling' and improving code organization.