react-best-practices
Use when the user needs React-specific patterns — hooks, component composition, Server Components, error boundaries, rendering optimization, and testing strategies. Triggers: hooks design, component composition, Server vs Client component decision, error boundary placement, context optimization, rendering performance.
What this skill does
# React Best Practices
## Overview
Apply modern React patterns to build maintainable, performant, and testable applications. This skill covers React 18/19 features including Server Components, hooks best practices, component composition, error boundaries, Suspense, context optimization, and rendering performance. It complements the senior-frontend skill with React-specific depth.
**Announce at start:** "I'm using the react-best-practices skill for React-specific patterns."
---
## Phase 1: Analyze Component Requirements
**Goal:** Understand the component's responsibility and data requirements before coding.
### Actions
1. Identify the component's single responsibility
2. Determine data requirements (server vs client data)
3. Choose Server Component (default) or Client Component
4. Identify state management needs
5. Plan error and loading states
### Server vs Client Decision Table
| Need | Component Type | Reason |
|------|---------------|--------|
| Direct data fetching (DB, API) | Server (default) | No client JS, faster |
| Event handlers (onClick, onChange) | Client (`'use client'`) | Needs browser interactivity |
| useState / useReducer | Client | State requires client runtime |
| useEffect / useLayoutEffect | Client | Side effects require client |
| Browser APIs (window, localStorage) | Client | Server has no browser |
| Third-party libs using client features | Client | Library requires client |
| No interactivity needed | Server (default) | Smaller bundle, faster |
### STOP — Do NOT proceed to Phase 2 until:
- [ ] Component responsibility is defined (single purpose)
- [ ] Server vs Client decision is made with rationale
- [ ] Data requirements are mapped
---
## Phase 2: Implement with Appropriate Patterns
**Goal:** Apply the correct React patterns for the component's needs.
### Actions
1. Apply appropriate composition pattern
2. Implement hooks correctly
3. Add error boundaries and Suspense
4. Optimize rendering where profiling shows need
5. Write tests that verify behavior
### STOP — Do NOT proceed to Phase 3 until:
- [ ] Patterns match the component's actual needs
- [ ] No unnecessary complexity (no premature optimization)
- [ ] Tests cover user-visible behavior
---
## Phase 3: Test and Verify
**Goal:** Verify component behavior through tests.
### Actions
1. Write tests using accessible queries
2. Test user interactions and outcomes
3. Test error and loading states
4. Verify accessibility
### Query Priority (React Testing Library)
| Priority | Query | Use For |
|----------|-------|---------|
| 1st | `getByRole` | Any element with ARIA role |
| 2nd | `getByLabelText` | Form fields |
| 3rd | `getByPlaceholderText` | Fields without labels |
| 4th | `getByText` | Non-interactive elements |
| Last | `getByTestId` | When nothing else works |
### STOP — Testing complete when:
- [ ] User interactions produce expected outcomes
- [ ] Error states are tested
- [ ] Accessibility checks pass
---
## Hooks Best Practices
### useState
```typescript
// Functional updates for state based on previous state
setCount(prev => prev + 1);
// Lazy initialization for expensive initial values
const [data, setData] = useState(() => computeExpensiveInitialValue());
// Group related state
const [form, setForm] = useState({ name: '', email: '', role: 'user' });
```
### useEffect
#### Dependency Array Rules
- Include ALL values from component scope that change over time
- Functions inside effect should be defined inside effect or wrapped in useCallback
- Never lie about dependencies (ESLint: `react-hooks/exhaustive-deps`)
#### Cleanup Pattern
```typescript
useEffect(() => {
const controller = new AbortController();
async function fetchData() {
try {
const res = await fetch(url, { signal: controller.signal });
const data = await res.json();
setData(data);
} catch (e) {
if (e.name !== 'AbortError') setError(e);
}
}
fetchData();
return () => controller.abort();
}, [url]);
```
#### When NOT to Use useEffect
| Instead of useEffect for... | Use This |
|----------------------------|----------|
| Data fetching | React Query, SWR, or Server Components |
| Transforming data | Compute during render |
| User events | Event handlers |
| Syncing external stores | `useSyncExternalStore` |
### Custom Hooks Rules
- Name starts with `use`
- Encapsulate reusable stateful logic
- One hook per concern
- Return object (not array) for > 2 values
```typescript
function useDebounce<T>(value: T, delay: number): T {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const timer = setTimeout(() => setDebouncedValue(value), delay);
return () => clearTimeout(timer);
}, [value, delay]);
return debouncedValue;
}
```
---
## Component Composition Patterns
### Compound Components
```typescript
function Tabs({ children, defaultValue }: TabsProps) {
const [activeTab, setActiveTab] = useState(defaultValue);
return (
<TabsContext.Provider value={{ activeTab, setActiveTab }}>
<div role="tablist">{children}</div>
</TabsContext.Provider>
);
}
Tabs.Tab = function Tab({ value, children }: TabProps) {
const { activeTab, setActiveTab } = useTabsContext();
return (
<button role="tab" aria-selected={activeTab === value} onClick={() => setActiveTab(value)}>
{children}
</button>
);
};
Tabs.Panel = function Panel({ value, children }: PanelProps) {
const { activeTab } = useTabsContext();
if (activeTab !== value) return null;
return <div role="tabpanel">{children}</div>;
};
```
### Composition Decision Table
| Pattern | Use When | Example |
|---------|----------|---------|
| Compound Components | Related components sharing implicit state | Tabs, Accordion, Menu |
| Slots (Children) | Complex content layout | Card with Header/Body/Footer |
| Render Props | Child needs parent data for flexible rendering | DataFetcher with custom render |
| Higher-Order Component | Cross-cutting concerns (legacy) | withAuth, withTheme |
| Custom Hook | Reusable stateful logic without UI | useDebounce, useLocalStorage |
### Slots Pattern
```typescript
// Prefer composition over props for complex content
// Bad
<Card title="Hello" subtitle="World" icon={<Star />} actions={<Button>Edit</Button>} />
// Good
<Card>
<Card.Header>
<Card.Icon><Star /></Card.Icon>
<Card.Title>Hello</Card.Title>
</Card.Header>
<Card.Actions>
<Button>Edit</Button>
</Card.Actions>
</Card>
```
---
## Error Boundaries
### Placement Strategy Decision Table
| Level | Purpose | Example |
|-------|---------|---------|
| Route level | Catch page-level crashes | `error.tsx` in Next.js |
| Feature level | Isolate feature failures | Wrap each major section |
| Data level | Wrap async data components | Around Suspense boundaries |
| Never leaf level | Too granular, adds noise | Do not wrap individual buttons |
---
## Suspense
```typescript
// Nested Suspense for granular loading
<Suspense fallback={<PageSkeleton />}>
<Header />
<Suspense fallback={<SidebarSkeleton />}>
<Sidebar />
</Suspense>
<Suspense fallback={<ContentSkeleton />}>
<MainContent />
</Suspense>
</Suspense>
```
---
## Context Optimization
### Problem: Context causes unnecessary re-renders
### Solution Decision Table
| Technique | Use When | Example |
|-----------|----------|---------|
| Split contexts by frequency | Some values update often, some rarely | ThemeContext (rare) vs UIStateContext (frequent) |
| Memoize context value | Provider re-renders with same data | `useMemo(() => ({ state, dispatch }), [state])` |
| Use selectors (Zustand/Jotai) | Need fine-grained subscriptions | `useStore(state => state.user.name)` |
| Lift state up | Only parent needs to re-render | Pass data as props to memoized children |
---
## Rendering Optimization
### Memoization Decision Table
| Technique | Use When | Do NOT Use When |
|-----------|----------|----------------|
| `React.memo` | Renders 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.