JAVASCRIPT
Global State with React `useContext` for Theming
Implement a global theme toggle in React using `useContext` and `useState` to share state across components, avoiding prop drilling for cleaner code.
import React, { useState, useContext, createContext } from 'react';
// 1. Create a Context
const ThemeContext = createContext(null);
// 2. Create a Provider component
function 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 easily
function useTheme() {
const context = useContext(ThemeContext);
if (context === null) {
throw new Error('useTheme must be used within a ThemeProvider');
}
return context;
}
// Example Usage:
// function ThemeToggle() {
// const { theme, toggleTheme } = useTheme();
// return (
// <button onClick={toggleTheme}>
// Switch to {theme === 'light' ? 'dark' : 'light'} Theme
// </button>
// );
// }
// function MyThemedComponent() {
// const { theme } = useTheme();
// return (
// <div style={{ background: theme === 'light' ? '#eee' : '#333', color: theme === 'light' ? '#333' : '#eee', padding: '20px' }}>
// Current Theme: {theme}
// <ThemeToggle />
// </div>
// );
// }
// function App() {
// return (
// <ThemeProvider>
// <MyThemedComponent />
// </ThemeProvider>
// );
// }
How it works: This snippet demonstrates how to use `useContext` and `createContext` to manage global state, specifically a theme preference, across your React application. A `ThemeProvider` component wraps children components, making the theme state and a `toggleTheme` function available via the `ThemeContext`. The `useTheme` custom hook simplifies consuming this context, allowing any nested component to access and update the theme without prop drilling.