Context API
What is Context?
The Context API enables sharing data between components without prop drilling. It is ideal for themes, authentication, and language.
Creating and Using Context
import { createContext, useContext, useState } from 'react';
const ThemeContext = createContext('light');
function App() {
const [theme, setTheme] = useState('dark');
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
<Toolbar />
</ThemeContext.Provider>
);
}
function Toolbar() {
const { theme, setTheme } = useContext(ThemeContext);
return (
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Theme: {theme}
</button>
);
}
createContext(defaultValue) — the default value is used when there is no Provider above.
Multiple Contexts
<ThemeContext.Provider value="dark">
<AuthContext.Provider value={{ user, login }}>
<LanguageContext.Provider value="id">
<MainApp />
</LanguageContext.Provider>
</AuthContext.Provider>
</ThemeContext.Provider>
Context Performance
When context changes = all consumers re-render. Separate static and dynamic contexts:
const ThemeStateContext = createContext('light');
const ThemeDispatchContext = createContext(() => {});
| Strategy | Benefit |
|---|---|
| Separate state/dispatch | Reduces re-renders |
| Combine static contexts | Reduces the number of Providers |
| Memoize the value in the Provider | Stabilizes the reference |
Context reduces prop drilling but is not a replacement for Redux for complex state. Next: styling approaches in React.