Careeroza
Context Basics
Three Steps
- Create a context:
const ThemeContext = createContext("light") - Provide a value high in the tree:
<ThemeContext.Provider value={theme}> - Read it in any child:
const theme = useContext(ThemeContext)
Theme Switcher
Example
Toolbar does not receive or pass any props; ThemedButton reads the theme directly.
import { createContext, useContext, useState } from 'react';
const ThemeContext = createContext('light');
function ThemedButton() {
const theme = useContext(ThemeContext);
const style = theme === 'dark'
? { background: '#222', color: '#fff' }
: { background: '#fff', color: '#222' };
return <button style={style}>I am {theme}</button>;
}
function Toolbar() {
return <div><ThemedButton /> <ThemedButton /></div>;
}
export default function App() {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={theme}>
<Toolbar />
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>Toggle theme</button>
</ThemeContext.Provider>
);
}Result