react
React 18+ library for building user interfaces. Covers components, hooks, state management, and rendering patterns. USE WHEN: user mentions "React component", "useState", "useEffect", "hooks", asks about "building UI", "component lifecycle", "React rendering", "JSX" DO NOT USE FOR: React 19 features - use `react-19` instead, React Router - use `react-router` instead, performance optimization - use `react-performance` instead
What this skill does
# React Core Knowledge
> **Deep Knowledge**: Use `mcp__documentation__fetch_docs` with technology: `react` for comprehensive documentation on hooks, components, and React patterns.
## Component Patterns
### Functional Components (Preferred)
```tsx
function UserCard({ name, email }: UserCardProps) {
return (
<div className="card">
<h2>{name}</h2>
<p>{email}</p>
</div>
);
}
```
### Props Typing
```tsx
interface Props {
title: string;
count?: number;
children: React.ReactNode;
onClick: (id: string) => void;
}
```
## Essential Hooks
| Hook | Purpose |
|------|---------|
| `useState` | Local state |
| `useEffect` | Side effects, subscriptions |
| `useContext` | Access context values |
| `useRef` | DOM refs, mutable values |
| `useMemo` | Memoize expensive computations |
| `useCallback` | Memoize functions |
| `useReducer` | Complex state logic |
## Key Patterns
- **Composition over inheritance**
- **Lift state up** for shared state
- **Props drilling** → use Context or state library
- **Controlled vs Uncontrolled** inputs
## Performance
- Use `React.memo()` for expensive pure components
- Memoize with `useMemo`/`useCallback` only when needed
- Use `key` prop correctly in lists
- Lazy load with `React.lazy()` + `Suspense`
## Production Readiness
### Security Best Practices
```tsx
// NEVER use dangerouslySetInnerHTML with user input
// BAD
<div dangerouslySetInnerHTML={{ __html: userInput }} />
// GOOD - Sanitize with DOMPurify
import DOMPurify from 'dompurify';
<div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(userInput) }} />
// Avoid exposing sensitive data in client-side state
// BAD
const [apiKey, setApiKey] = useState(process.env.API_KEY);
// GOOD - API keys should stay server-side
// Use API routes or server actions instead
// Validate all external URLs
const isValidUrl = (url: string) => {
try {
const parsed = new URL(url);
return ['http:', 'https:'].includes(parsed.protocol);
} catch {
return false;
}
};
```
### Error Boundaries
```tsx
import { ErrorBoundary } from 'react-error-boundary';
function ErrorFallback({ error, resetErrorBoundary }: FallbackProps) {
return (
<div role="alert">
<p>Something went wrong:</p>
<pre>{error.message}</pre>
<button onClick={resetErrorBoundary}>Try again</button>
</div>
);
}
// Usage
<ErrorBoundary
FallbackComponent={ErrorFallback}
onReset={() => window.location.reload()}
onError={(error, info) => {
// Log to error reporting service
logErrorToService(error, info);
}}
>
<App />
</ErrorBoundary>
```
### Performance Optimization
```tsx
// Code splitting with lazy loading
const Dashboard = lazy(() => import('./Dashboard'));
function App() {
return (
<Suspense fallback={<Skeleton />}>
<Dashboard />
</Suspense>
);
}
// Memoization - use sparingly, only for expensive components
const ExpensiveList = memo(function ExpensiveList({ items }: Props) {
return items.map(item => <ExpensiveItem key={item.id} {...item} />);
});
// Virtualization for large lists
import { FixedSizeList } from 'react-window';
function VirtualList({ items }: { items: Item[] }) {
return (
<FixedSizeList
height={400}
itemCount={items.length}
itemSize={50}
width="100%"
>
{({ index, style }) => (
<div style={style}>{items[index].name}</div>
)}
</FixedSizeList>
);
}
```
### Accessibility (a11y)
```tsx
// Use semantic HTML
<button onClick={handleClick}>Submit</button> // NOT <div onClick>
// ARIA labels for icons/images
<button aria-label="Close dialog" onClick={onClose}>
<XIcon />
</button>
// Focus management
const dialogRef = useRef<HTMLDivElement>(null);
useEffect(() => {
dialogRef.current?.focus();
}, [isOpen]);
// Keyboard navigation
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape') onClose();
if (e.key === 'Tab') trapFocus(e);
};
```
### Testing Setup
```tsx
// Component testing with Testing Library
import { render, screen, userEvent } from '@testing-library/react';
test('submits form with user data', async () => {
const onSubmit = vi.fn();
render(<Form onSubmit={onSubmit} />);
await userEvent.type(screen.getByLabelText(/email/i), '[email protected]');
await userEvent.click(screen.getByRole('button', { name: /submit/i }));
expect(onSubmit).toHaveBeenCalledWith({ email: '[email protected]' });
});
```
### Monitoring Metrics
| Metric | Alert Threshold |
|--------|-----------------|
| Largest Contentful Paint (LCP) | > 2.5s |
| First Input Delay (FID) | > 100ms |
| Cumulative Layout Shift (CLS) | > 0.1 |
| JavaScript bundle size | > 200KB (gzipped) |
| Component render time | > 16ms |
### Build & Bundle Optimization
```typescript
// vite.config.ts
export default defineConfig({
build: {
rollupOptions: {
output: {
manualChunks: {
vendor: ['react', 'react-dom'],
ui: ['@radix-ui/react-dialog', '@radix-ui/react-dropdown'],
},
},
},
sourcemap: true, // For error tracking in production
},
});
```
### Checklist
- [ ] Error boundaries wrapping critical sections
- [ ] No sensitive data in client state
- [ ] DOMPurify for any HTML rendering
- [ ] Lazy loading for route-based code splitting
- [ ] Virtualization for large lists (>100 items)
- [ ] Semantic HTML and ARIA labels
- [ ] Keyboard navigation support
- [ ] Core Web Vitals monitored
- [ ] Bundle size optimized (<200KB gzip)
- [ ] Source maps for production debugging
- [ ] Error reporting service integrated
## When NOT to Use This Skill
- **React 19 specific features** (Actions, useActionState, use()) - Use `react-19` skill instead
- **Advanced performance optimization** - Use `react-performance` skill instead
- **Form handling patterns** - Use `react-forms` or `react-hook-form` skills instead
- **Routing** - Use `react-router` skill instead
- **Testing** - Use `react-testing` skill instead
- **Component design patterns** - Use `react-patterns` skill instead
## Anti-Patterns
| Anti-Pattern | Problem | Solution |
|--------------|---------|----------|
| Mutating state directly | Doesn't trigger re-render | Use setState with new object/array |
| Missing dependency arrays | Stale closures, memory leaks | Include all dependencies or use ESLint |
| useEffect for derived state | Extra re-renders | Calculate during render or use useMemo |
| Props drilling deeply | Hard to maintain | Use Context or state library |
| Inline object/array in JSX | Breaks memoization | Extract to constant or useMemo |
| New functions in render | Child re-renders unnecessarily | Use useCallback |
| Forgetting cleanup in useEffect | Memory leaks | Return cleanup function |
| Using index as key | Incorrect re-renders | Use stable unique ID |
## Quick Troubleshooting
| Issue | Likely Cause | Fix |
|-------|--------------|-----|
| Component not re-rendering | State mutation | Use setState with new reference |
| Infinite loop in useEffect | Missing/wrong dependencies | Add deps or use functional update |
| "Cannot read property of undefined" | Async data not loaded | Add null checks or loading state |
| Memory leak warning | Missing cleanup | Return cleanup function from useEffect |
| Children not updating | Using index as key | Use unique stable ID |
| Handler not firing | Event propagation stopped | Check stopPropagation() calls |
| Stale state in callback | Closure over old state | Use functional setState |
## Reference Documentation
- [Hooks Cheatsheet](quick-ref/hooks-cheatsheet.md)
- [Component Patterns](quick-ref/component-patterns.md)
- [Deep: Hooks Guide](deep-docs/hooks/)
- [Deep: Performance](deep-docs/performance/)
Related 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.