Sharing State with Context
The Context API solves the prop drilling problem — when you need to pass data through many layers of components that don't use it themselves. Context lets you share values across the component tree without explicitly passing props at every level.
Context is ideal for global data like themes, authentication, language preferences, or user settings.
Example
import { createContext, useContext, useState } from 'react';
// 1. Create the context
const ThemeContext = createContext();
// 2. Create a provider component
function ThemeProvider({ children }) {
const [theme, setTheme] = useState('light');
const toggleTheme = () => {
setTheme(prev => prev === 'light' ? 'dark' : 'light');
};
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
{children}
</ThemeContext.Provider>
);
}
// 3. Use the context in any child component
function Header() {
const { theme, toggleTheme } = useContext(ThemeContext);
return (
<header className={theme}>
<h1>My App</h1>
<button onClick={toggleTheme}>
Switch to {theme === 'light' ? 'dark' : 'light'}
</button>
</header>
);
}
// 4. Wrap your app with the provider
function App() {
return (
<ThemeProvider>
<Header />
<main>Content here</main>
</ThemeProvider>
);
} - createContext() — Creates a context object
- Provider — Wraps components that need access to the context value
- useContext(Context) — Consumes the context value in a component
- Context avoids prop drilling through intermediate components
- Best for: theme, auth, locale, user preferences
Notes
- Don't overuse Context for everything. It's best for truly global data. For state shared between a few nearby components, lifting state up is simpler.
