React Context
Full Reference: See advanced.md for context selectors with useSyncExternalStore, dependency injection, React 19 use(), testing context, and TypeScript patterns.
Deep Knowledge: Use mcp__documentation__fetch_docs with technology: react topic: context for comprehensive documentation.
Basic Usage
import { createContext, useContext, ReactNode } from 'react';
// 1. Create context with default value
interface ThemeContextValue {
theme: 'light' | 'dark';
toggleTheme: () => void;
}
const ThemeContext = createContext<ThemeContextValue | null>(null);
// 2. Create Provider component
function ThemeProvider({ children }: { children: ReactNode }) {
const [theme, setTheme] = useState<'light' | 'dark'>('light');
const toggleTheme = useCallback(() => {
setTheme(prev => prev === 'light' ? 'dark' : 'light');
}, []);
const value = useMemo(() => ({ theme, toggleTheme }), [theme, toggleTheme]);
return (
<ThemeContext.Provider value={value}>
{children}
</ThemeContext.Provider>
);
}
// 3. Create custom hook for consuming
function useTheme() {
const context = useContext(ThemeContext);
if (!context) {
throw new Error('useTheme must be used within a ThemeProvider');
}
return context;
}
// 4. Use in components
function Header() {
const { theme, toggleTheme } = useTheme();
return (
<header className={theme}>
<button
Switch to {theme === 'light' ? 'dark' : 'light'}
</button>
</header>
);
}
// 5. Wrap app with provider
function App() {
return (
<ThemeProvider>
<Header />
<Main />
</ThemeProvider>
);
}
Context with Reducer
For complex state management:
interface AuthState {
user: User | null;
isLoading: boolean;
error: string | null;
}
type AuthAction =
| { type: 'LOGIN_START' }
| { type: 'LOGIN_SUCCESS'; payload: User }
| { type: 'LOGIN_ERROR'; payload: string }
| { type: 'LOGOUT' };
const initialState: AuthState = {
user: null,
isLoading: false,
error: null,
};
function authReducer(state: AuthState, action: AuthAction): AuthState {
switch (action.type) {
case 'LOGIN_START':
return { ...state, isLoading: true, error: null };
case 'LOGIN_SUCCESS':
return { ...state, isLoading: false, user: action.payload };
case 'LOGIN_ERROR':
return { ...state, isLoading: false, error: action.payload };
case 'LOGOUT':
return initialState;
default:
return state;
}
}
// Separate state and dispatch contexts for optimization
const AuthStateContext = createContext<AuthState | null>(null);
const AuthDispatchContext = createContext<React.Dispatch<AuthAction> | null>(null);
function AuthProvider({ children }: { children: ReactNode }) {
const [state, dispatch] = useReducer(authReducer, initialState);
return (
<AuthStateContext.Provider value={state}>
<AuthDispatchContext.Provider value={dispatch}>
{children}
</AuthDispatchContext.Provider>
</AuthStateContext.Provider>
);
}
// Custom hooks
function useAuthState() {
const context = useContext(AuthStateContext);
if (!context) {
throw new Error('useAuthState must be used within AuthProvider');
}
return context;
}
function useAuthDispatch() {
const context = useContext(AuthDispatchContext);
if (!context) {
throw new Error('useAuthDispatch must be used within AuthProvider');
}
return context;
}
Performance Optimization
Split State and Actions
// Problem: All consumers re-render when any value changes
const BadContext = createContext({ count: 0, increment: () => {} });
// Solution: Separate frequently changing values
const CountContext = createContext(0);
const CountActionsContext = createContext({ increment: () => {} });
function CountProvider({ children }: { children: ReactNode }) {
const [count, setCount] = useState(0);
// Memoize actions object
const actions = useMemo(() => ({
increment: () => setCount(c => c + 1),
decrement: () => setCount(c => c - 1),
reset: () => setCount(0),
}), []);
return (
<CountContext.Provider value={count}>
<CountActionsContext.Provider value={actions}>
{children}
</CountActionsContext.Provider>
</CountContext.Provider>
);
}
// Now components can subscribe to only what they need
function DisplayCount() {
const count = useContext(CountContext);
console.log('DisplayCount rendered'); // Only when count changes
return <span>{count}</span>;
}
function IncrementButton() {
const { increment } = useContext(CountActionsContext);
console.log('IncrementButton rendered'); // Never re-renders!
return <button
}
Context Composition
Combine multiple contexts cleanly:
// Compose multiple providers
function AppProviders({ children }: { children: ReactNode }) {
return (
<ThemeProvider>
<AuthProvider>
<SettingsProvider>
<NotificationsProvider>
{children}
</NotificationsProvider>
</SettingsProvider>
</AuthProvider>
</ThemeProvider>
);
}
// Or use a composition helper
type ProviderProps = { children: ReactNode };
type Provider = React.ComponentType<ProviderProps>;
function composeProviders(...providers: Provider[]) {
return function ComposedProvider({ children }: ProviderProps) {
return providers.reduceRight(
(child, Provider) => <Provider>{child}</Provider>,
children
);
};
}
const AppProviders = composeProviders(
ThemeProvider,
AuthProvider,
SettingsProvider,
NotificationsProvider
);
// Usage
function App() {
return (
<AppProviders>
<Router />
</AppProviders>
);
}
Context vs Other State Solutions
| Solution |
Use Case |
| Context |
Dependency injection, theme, auth, rarely changing data |
| useState |
Local component state |
| useReducer |
Complex local state logic |
| Zustand/Jotai |
Frequent updates, performance critical |
| TanStack Query |
Server state, caching |
| Redux |
Large apps, time-travel debugging |
When NOT to Use Context
// ❌ Frequently changing data (causes unnecessary re-renders)
const PositionContext = createContext({ x: 0, y: 0 });
// ✅ Use a proper state library instead
const useMouseStore = create((set) => ({
position: { x: 0, y: 0 },
setPosition: (pos) => set({ position: pos }),
}));
// ❌ Complex nested updates
const FormContext = createContext({
values: {},
errors: {},
touched: {},
// ...many more fields
});
// ✅ Use a form library
const { register, handleSubmit } = useForm();
Common Pitfalls
| Issue |
Cause |
Solution |
| Unnecessary re-renders |
Context value not memoized |
Use useMemo for value |
| "Cannot read undefined" |
Missing Provider |
Add null check or throw in hook |
| Stale closures |
Missing dependencies |
Add to dependency array |
| Performance issues |
Large frequently updating context |
Split into multiple contexts |
Best Practices
- Always create custom hooks for consuming context
- Memoize context value with useMemo
- Split state and dispatch into separate contexts
- Use TypeScript for type safety
- Throw error if context used outside provider
- Don't use context for frequently changing values
- Don't pass entire state when only part is needed
- Don't deeply nest too many providers
When NOT to Use This Skill
- React 19 use() hook - Use
react-19 skill for conditional context reading
- State management libraries - Use Zustand, Redux, or Jotai skills for complex state
- Server state - Use TanStack Query skill for data fetching and caching
- Form state - Use React Hook Form skill for form-specific state
Anti-Patterns
| Anti-Pattern |
Problem |
Solution |
| Context for frequently changing values |
Performance issues, many re-renders |
Use state library (Zustand) or useSyncExternalStore |
| Not memoizing context value |
New object every render, all consumers re-render |
Use useMemo for context value |
| Single context with all state |
Unnecessary re-renders |
Split into multiple focused contexts |
| Not throwing in custom hook |
Poor error messages |
Throw error if context is null/undefined |
| Deeply nested providers |
Hard to read, maintain |
Use provider composition helper |
| Context for local component state |
Unnecessary complexity |
Use useState in component |
| Default value that's never used |
Misleading |
Use null/undefined and throw in hook |
Quick Troubleshooting
| Issue |
Likely Cause |
Fix |
| "Cannot read property of undefined" |
Missing Provider |
Wrap component tree with Provider |
| All consumers re-rendering |
Context value not memoized |
Wrap value in useMemo |
| Context value undefined |
Used outside Provider |
Check Provider wraps component |
| Poor performance |
Large frequently-changing context |
Split context or use state library |
| Type errors |
Wrong context type |
Check TypeScript generic in createContext |
| Stale values |
Missing dependencies |
Add values to useMemo dependencies |
| Nested providers confusing |
Too many providers |
Use composition helper function |
Reference Documentation
1---2name: react-context3description: |4 React Context API for state sharing across component trees. Covers createContext,5 useContext, Provider patterns, performance optimization, context composition,6 and when to use vs other state solutions.78 USE WHEN: user mentions "React Context", "createContext", "useContext", "Provider",9 "Context API", "dependency injection", asks about "avoiding prop drilling",10 "global state in React", "context composition"1112 DO NOT USE FOR: React 19 use() hook with Context - use `react-19` skill instead,13 state management libraries - use specific library skills (Zustand, Redux, etc.),14 server state - use TanStack Query skill instead15allowed-tools: Read, Grep, Glob, Write, Edit16metadata:17 source: https://skillmd.com/skills/claude-dev-suite/react-context18---1920# React Context2122> **Full Reference**: See [advanced.md](advanced.md) for context selectors with useSyncExternalStore, dependency injection, React 19 use(), testing context, and TypeScript patterns.2324> **Deep Knowledge**: Use `mcp__documentation__fetch_docs` with technology: `react` topic: `context` for comprehensive documentation.2526## Basic Usage2728```tsx29import { createContext, useContext, ReactNode } from 'react';3031// 1. Create context with default value32interface ThemeContextValue {33 theme: 'light' | 'dark';34 toggleTheme: () => void;35}3637const ThemeContext = createContext<ThemeContextValue | null>(null);3839// 2. Create Provider component40function ThemeProvider({ children }: { children: ReactNode }) {41 const [theme, setTheme] = useState<'light' | 'dark'>('light');4243 const toggleTheme = useCallback(() => {44 setTheme(prev => prev === 'light' ? 'dark' : 'light');45 }, []);4647 const value = useMemo(() => ({ theme, toggleTheme }), [theme, toggleTheme]);4849 return (50 <ThemeContext.Provider value={value}>51 {children}52 </ThemeContext.Provider>53 );54}5556// 3. Create custom hook for consuming57function useTheme() {58 const context = useContext(ThemeContext);59 if (!context) {60 throw new Error('useTheme must be used within a ThemeProvider');61 }62 return context;63}6465// 4. Use in components66function Header() {67 const { theme, toggleTheme } = useTheme();6869 return (70 <header className={theme}>71 <button onClick={toggleTheme}>72 Switch to {theme === 'light' ? 'dark' : 'light'}73 </button>74 </header>75 );76}7778// 5. Wrap app with provider79function App() {80 return (81 <ThemeProvider>82 <Header />83 <Main />84 </ThemeProvider>85 );86}87```8889---9091## Context with Reducer9293For complex state management:9495```tsx96interface AuthState {97 user: User | null;98 isLoading: boolean;99 error: string | null;100}101102type AuthAction =103 | { type: 'LOGIN_START' }104 | { type: 'LOGIN_SUCCESS'; payload: User }105 | { type: 'LOGIN_ERROR'; payload: string }106 | { type: 'LOGOUT' };107108const initialState: AuthState = {109 user: null,110 isLoading: false,111 error: null,112};113114function authReducer(state: AuthState, action: AuthAction): AuthState {115 switch (action.type) {116 case 'LOGIN_START':117 return { ...state, isLoading: true, error: null };118 case 'LOGIN_SUCCESS':119 return { ...state, isLoading: false, user: action.payload };120 case 'LOGIN_ERROR':121 return { ...state, isLoading: false, error: action.payload };122 case 'LOGOUT':123 return initialState;124 default:125 return state;126 }127}128129// Separate state and dispatch contexts for optimization130const AuthStateContext = createContext<AuthState | null>(null);131const AuthDispatchContext = createContext<React.Dispatch<AuthAction> | null>(null);132133function AuthProvider({ children }: { children: ReactNode }) {134 const [state, dispatch] = useReducer(authReducer, initialState);135136 return (137 <AuthStateContext.Provider value={state}>138 <AuthDispatchContext.Provider value={dispatch}>139 {children}140 </AuthDispatchContext.Provider>141 </AuthStateContext.Provider>142 );143}144145// Custom hooks146function useAuthState() {147 const context = useContext(AuthStateContext);148 if (!context) {149 throw new Error('useAuthState must be used within AuthProvider');150 }151 return context;152}153154function useAuthDispatch() {155 const context = useContext(AuthDispatchContext);156 if (!context) {157 throw new Error('useAuthDispatch must be used within AuthProvider');158 }159 return context;160}161```162163---164165## Performance Optimization166167### Split State and Actions168169```tsx170// Problem: All consumers re-render when any value changes171const BadContext = createContext({ count: 0, increment: () => {} });172173// Solution: Separate frequently changing values174const CountContext = createContext(0);175const CountActionsContext = createContext({ increment: () => {} });176177function CountProvider({ children }: { children: ReactNode }) {178 const [count, setCount] = useState(0);179180 // Memoize actions object181 const actions = useMemo(() => ({182 increment: () => setCount(c => c + 1),183 decrement: () => setCount(c => c - 1),184 reset: () => setCount(0),185 }), []);186187 return (188 <CountContext.Provider value={count}>189 <CountActionsContext.Provider value={actions}>190 {children}191 </CountActionsContext.Provider>192 </CountContext.Provider>193 );194}195196// Now components can subscribe to only what they need197function DisplayCount() {198 const count = useContext(CountContext);199 console.log('DisplayCount rendered'); // Only when count changes200 return <span>{count}</span>;201}202203function IncrementButton() {204 const { increment } = useContext(CountActionsContext);205 console.log('IncrementButton rendered'); // Never re-renders!206 return <button onClick={increment}>+</button>;207}208```209210---211212## Context Composition213214Combine multiple contexts cleanly:215216```tsx217// Compose multiple providers218function AppProviders({ children }: { children: ReactNode }) {219 return (220 <ThemeProvider>221 <AuthProvider>222 <SettingsProvider>223 <NotificationsProvider>224 {children}225 </NotificationsProvider>226 </SettingsProvider>227 </AuthProvider>228 </ThemeProvider>229 );230}231232// Or use a composition helper233type ProviderProps = { children: ReactNode };234type Provider = React.ComponentType<ProviderProps>;235236function composeProviders(...providers: Provider[]) {237 return function ComposedProvider({ children }: ProviderProps) {238 return providers.reduceRight(239 (child, Provider) => <Provider>{child}</Provider>,240 children241 );242 };243}244245const AppProviders = composeProviders(246 ThemeProvider,247 AuthProvider,248 SettingsProvider,249 NotificationsProvider250);251252// Usage253function App() {254 return (255 <AppProviders>256 <Router />257 </AppProviders>258 );259}260```261262---263264## Context vs Other State Solutions265266| Solution | Use Case |267|----------|----------|268| Context | Dependency injection, theme, auth, rarely changing data |269| useState | Local component state |270| useReducer | Complex local state logic |271| Zustand/Jotai | Frequent updates, performance critical |272| TanStack Query | Server state, caching |273| Redux | Large apps, time-travel debugging |274275### When NOT to Use Context276277```tsx278// ❌ Frequently changing data (causes unnecessary re-renders)279const PositionContext = createContext({ x: 0, y: 0 });280281// ✅ Use a proper state library instead282const useMouseStore = create((set) => ({283 position: { x: 0, y: 0 },284 setPosition: (pos) => set({ position: pos }),285}));286287// ❌ Complex nested updates288const FormContext = createContext({289 values: {},290 errors: {},291 touched: {},292 // ...many more fields293});294295// ✅ Use a form library296const { register, handleSubmit } = useForm();297```298299---300301## Common Pitfalls302303| Issue | Cause | Solution |304|-------|-------|----------|305| Unnecessary re-renders | Context value not memoized | Use useMemo for value |306| "Cannot read undefined" | Missing Provider | Add null check or throw in hook |307| Stale closures | Missing dependencies | Add to dependency array |308| Performance issues | Large frequently updating context | Split into multiple contexts |309310## Best Practices311312- Always create custom hooks for consuming context313- Memoize context value with useMemo314- Split state and dispatch into separate contexts315- Use TypeScript for type safety316- Throw error if context used outside provider317- Don't use context for frequently changing values318- Don't pass entire state when only part is needed319- Don't deeply nest too many providers320321## When NOT to Use This Skill322323- **React 19 use() hook** - Use `react-19` skill for conditional context reading324- **State management libraries** - Use Zustand, Redux, or Jotai skills for complex state325- **Server state** - Use TanStack Query skill for data fetching and caching326- **Form state** - Use React Hook Form skill for form-specific state327328## Anti-Patterns329330| Anti-Pattern | Problem | Solution |331|--------------|---------|----------|332| Context for frequently changing values | Performance issues, many re-renders | Use state library (Zustand) or useSyncExternalStore |333| Not memoizing context value | New object every render, all consumers re-render | Use useMemo for context value |334| Single context with all state | Unnecessary re-renders | Split into multiple focused contexts |335| Not throwing in custom hook | Poor error messages | Throw error if context is null/undefined |336| Deeply nested providers | Hard to read, maintain | Use provider composition helper |337| Context for local component state | Unnecessary complexity | Use useState in component |338| Default value that's never used | Misleading | Use null/undefined and throw in hook |339340## Quick Troubleshooting341342| Issue | Likely Cause | Fix |343|-------|--------------|-----|344| "Cannot read property of undefined" | Missing Provider | Wrap component tree with Provider |345| All consumers re-rendering | Context value not memoized | Wrap value in useMemo |346| Context value undefined | Used outside Provider | Check Provider wraps component |347| Poor performance | Large frequently-changing context | Split context or use state library |348| Type errors | Wrong context type | Check TypeScript generic in createContext |349| Stale values | Missing dependencies | Add values to useMemo dependencies |350| Nested providers confusing | Too many providers | Use composition helper function |351352## Reference Documentation353354- [React Context](https://react.dev/reference/react/useContext)355- [Scaling Up with Reducer and Context](https://react.dev/learn/scaling-up-with-reducer-and-context)356- MCP: `mcp__documentation__fetch_docs` → technology: `react`, topic: `context`