react-context
React Context API for state sharing across component trees. Covers createContext, useContext, Provider patterns, performance optimization, context composition, and when to use vs other state solutions. USE WHEN: user mentions "React Context", "createContext", "useContext", "Provider", "Context API", "dependency injection", asks about "avoiding prop drilling", "global state in React", "context composition" DO NOT USE FOR: React 19 use() hook with Context - use `react-19` skill instead, state management libraries - use specific library skills (Zustand, Redux, etc.), server state - use TanStack Query skill instead
What this skill does
# React Context
> **Full Reference**: See [advanced.md](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
```tsx
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 onClick={toggleTheme}>
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:
```tsx
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
```tsx
// 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 onClick={increment}>+</button>;
}
```
---
## Context Composition
Combine multiple contexts cleanly:
```tsx
// 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
```tsx
// ❌ 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 issRelated in Design
contribute
IncludedLocal-only OSS contribution command center. Auto-refreshes the user's in-flight PR and issue state on invoke so conversations start with full context — no need to brief Claude on what's in flight. Helps the user find issues to contribute to on GitHub, builds per-repo dossiers of what each upstream expects (CLA, DCO, branch convention, AI policy, draft-first, review bots, issue templates), runs deterministic gates before any external action so AI-assisted contributions don't reach maintainers as slop. State is markdown-only: candidate files at ~/.contribute-system/candidates/, repo dossiers at ~/.contribute-system/research/, append-only event log at ~/.contribute-system/log.jsonl. No database, no cloud calls. Use when the user asks about their PRs / issues / contributions, wants to find new work to take on, claim an issue, build/refresh a repo's dossier, or draft a Design Issue or PR. Trigger with "/contribute", "what's my PR status", "find a contribution", "claim issue X", "draft a Design Issue for Y", "refresh dossier for Z".
architectural-analysis
IncludedUser-triggered deep architectural analysis of a codebase or scoped subtree across eight modes — information architecture, data flow, integration points, UI surfaces, interaction patterns, data model, control flow, and failure modes. This skill should be used when the user asks to "diagram this codebase," "map the architecture," "show the data flow," "give me an ERD," "trace control flow," "find the integration points," "verify the layout pattern," "audit the UX architecture," or any similar request whose primary deliverable is mermaid diagrams plus cited reports under docs/architecture/. Dispatches haiku/sonnet sub-agents in parallel for per-mode exploration, then verifies every citation mechanically before any node lands in a diagram. Not for one-off prose explanations of code (use code-explanation) or for high-level system design from scratch (use system-design).
mcp
IncludedModel Context Protocol (MCP) server development and tool management. Languages: Python, TypeScript. Capabilities: build MCP servers, integrate external APIs, discover/execute MCP tools, manage multi-server configs, design agent-centric tools. Actions: create, build, integrate, discover, execute, configure MCP servers/tools. Keywords: MCP, Model Context Protocol, MCP server, MCP tool, stdio transport, SSE transport, tool discovery, resource provider, prompt template, external API integration, Gemini CLI MCP, Claude MCP, agent tools, tool execution, server config. Use when: building MCP servers, integrating external APIs as MCP tools, discovering available MCP tools, executing MCP capabilities, configuring multi-server setups, designing tools for AI agents.
react-native-skia
IncludedDesign, build, debug, and optimise high-polish animated graphics in React Native or Expo using @shopify/react-native-skia, Reanimated, and Gesture Handler. Use when the user wants canvas-driven UI, shaders, paths, rich text, image filters, sprite fields, Skottie, video frames, snapshots, web CanvasKit setup, or performance tuning for custom motion-heavy elements such as loaders, hero art, cards, charts, progress indicators, particle systems, or gesture-driven surfaces. Also use when the user asks for fluid, glow, glass, blob, parallax, 60fps/120fps, or GPU-friendly animated effects in React Native, even if they do not explicitly say "Skia". Do not use for ordinary form/layout work with standard views.
plaid
IncludedProduct Led AI Development — guides founders from idea to launched product. Six capabilities: Idea (discover a product idea), Validate (pressure-test the idea against fatal flaws, problem reality, competition, and 2-week MVP feasibility), Plan (vision intake + document generation), Design (translate image references into a design.md spec), Launch (go-to-market strategy), and Build (roadmap execution). Use when someone says "PLAID", "plaid idea", "help me find an idea", "product idea", "idea from my business", "idea from my expertise", "plaid validate", "validate my idea", "pressure-test", "is this idea good", "find fatal flaws", "validate the problem", "plan a product", "define my vision", "generate a PRD", "product strategy", "plaid design", "design from image", "translate image to design", "create design.md", "extract design tokens", "plaid launch", "go-to-market", "launch plan", "GTM strategy", "launch playbook", "plaid build", "build the app", "start building", or "execute the roadmap".
nextjs-framer-motion-animations
IncludedAdds production-safe Motion for React or Framer Motion animations to Next.js apps, including reveal, hover and tap micro-interactions, whileInView, stagger, AnimatePresence, layout and layoutId transitions, reorder, scroll-linked UI, and lightweight route-content transitions. Use when the user asks to add, refactor, or debug Motion or Framer Motion in App Router or Pages Router codebases, especially around server/client boundaries, reduced motion, LazyMotion, bundle size, hydration, or route transitions. Avoid for GSAP-style timelines, WebGL or 3D scenes, heavy scroll storytelling, or CSS-only effects unless Motion is explicitly requested.