JAVASCRIPT
Global Theme Management with `useContext`
Learn to manage global themes (light/dark mode) in a React application using `useContext` to avoid prop drilling and provide state to deeply nested components.
import React, { createContext, useState, useContext } from 'react';
// 1. Create a Context
const ThemeContext = createContext(null);
// 2. Create a Provider Component
export const ThemeProvider = ({ children }) => {
const [theme, setTheme] = useState('light'); // 'light' or 'dark'
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
export const useTheme = () => {
const context = useContext(ThemeContext);
if (!context) {
throw new Error('useTheme must be used within a ThemeProvider');
}
return context;
};
// Example Usage:
// function MyApp() {
// return (
// <ThemeProvider>
// <Toolbar />
// </ThemeProvider>
// );
// }
// function Toolbar() {
// const { theme, toggleTheme } = useTheme();
// return (
// <div style={{ background: theme === 'dark' ? '#333' : '#eee', color: theme === 'dark' ? 'white' : 'black', padding: '1em' }}>
// Current Theme: {theme}
// <button onClick={toggleTheme} style={{ marginLeft: '1em' }}>
// Toggle Theme
// </button>
// </div>
// );
// }
How it works: This snippet demonstrates how to use React's Context API for global state management, specifically for a theme (light/dark mode). It involves creating a context, a provider component that holds the state and update logic, and a custom hook (`useTheme`) to easily consume the context in any child component. This pattern effectively avoids 'prop drilling,' where props have to be manually passed down through multiple levels of components.