Learn the concept
Context API
Context provides a way to pass data through the component tree without prop drilling. Use it for global data like themes, authentication, or locale. For frequently changing data or complex state logic, consider state management libraries instead.
What Context Solves:
How Context Works:
use(Context) (React 19+, preferred) or useContext() hookWhen to Use Context:
When NOT to Use Context:
React 19 Update:
use(Context) is preferred over useContext() — it can be called conditionally (inside if/else and loops)import { createContext, useContext, useState } from 'react';
// 1. Create context with default value
const ThemeContext = createContext('light');
// 2. Create 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. Custom hook for consuming (recommended)
function useTheme() {
const context = useContext(ThemeContext);
if (!context) {
throw new Error('useTheme must be used within ThemeProvider');
}
return context;
}
// 4. Use in components
function ThemedButton() {
const { theme, toggleTheme } = useTheme();
return (
<button
onClick={toggleTheme}
style={{ background: theme === 'dark' ? '#333' : '#fff' }}
>
Current: {theme}
</button>
);
}Providing theme configuration (colors, fonts, spacing) to all components without prop drilling
Sharing user auth state (token, user info, permissions) across the entire app
Providing locale and translation functions to all components via context
Build an app with context-based theme switching (light/dark/system) with CSS variable integration
Create a context-based feature flag provider that conditionally renders features based on user roles