React
Beginner
1 min read
Creating and Providing Context
Example
import { createContext, useContext, useState } from 'react';
// 1. Create context with a sensible default
const ThemeContext = createContext({
theme: 'light',
toggleTheme: () => {},
});
// 2. Provider component
export function ThemeProvider({ children }) {
const [theme, setTheme] = useState('light');
function toggleTheme() {
setTheme(t => (t === 'light' ? 'dark' : 'light'));
}
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
{children}
</ThemeContext.Provider>
);
}
// 3. Consumer — any depth in the tree
function ThemedButton({ children }) {
const { theme, toggleTheme } = useContext(ThemeContext);
return (
<button
onClick={toggleTheme}
style={{
background: theme === 'light' ? '#fff' : '#222',
color: theme === 'light' ? '#222' : '#fff',
}}
>
{children}
</button>
);
}
// 4. App root
export default function App() {
return (
<ThemeProvider>
<ThemedButton>Toggle Theme</ThemedButton>
</ThemeProvider>
);
}