react-best-practices
Guide complet des bonnes pratiques React et Next.js couvrant l'optimisation des performances, l'architecture des composants, les patrons shadcn/ui, les animations Motion et les patrons modernes React 19+. À utiliser lors de l'écriture, la revue ou le refactoring de code React/Next.js. Se déclenche sur les tâches impliquant des composants React, des pages Next.js, du data fetching, des composants UI, des animations ou de l'amélioration de la qualité du code.
What this skill does
# React Best Practices
Comprehensive guide for building modern React and Next.js applications. Covers performance optimization, component architecture, shadcn/ui patterns, Motion animations, accessibility, and React 19+ features.
## When to Apply
Reference these guidelines when:
- Writing new React components or Next.js pages
- Implementing data fetching (client or server-side)
- Building UI with shadcn/ui components
- Adding animations and micro-interactions
- Reviewing code for quality and performance
- Refactoring existing React/Next.js code
- Optimizing bundle size or load times
## Rule Categories by Priority
| Priority | Category | Impact | Prefix |
|----------|----------|--------|--------|
| 1 | Component Architecture | CRITICAL | `arch-` |
| 2 | Eliminating Waterfalls | CRITICAL | `async-` |
| 3 | Bundle Size Optimization | CRITICAL | `bundle-` |
| 4 | Server Components & Actions | HIGH | `server-` |
| 5 | shadcn/ui Patterns | HIGH | `shadcn-` |
| 6 | State Management | MEDIUM-HIGH | `state-` |
| 7 | Motion & Animations | MEDIUM | `motion-` |
| 8 | Re-render Optimization | MEDIUM | `rerender-` |
| 9 | Accessibility | MEDIUM | `a11y-` |
| 10 | TypeScript Patterns | MEDIUM | `ts-` |
---
## 1. Component Architecture (CRITICAL)
### Quick Reference
- `arch-functional-components` - Use functional components with hooks exclusively
- `arch-composition-over-inheritance` - Build on existing components, don't extend
- `arch-single-responsibility` - Each component should do one thing well
- `arch-presentational-container` - Separate UI from logic when beneficial
- `arch-colocation` - Keep related files together (component, styles, tests)
- `arch-avoid-prop-drilling` - Use Context or composition for deep props
### Key Principles
**Functional Components Only**
```typescript
// Correct: Functional component with hooks
function UserProfile({ userId }: { userId: string }) {
const { data: user } = useUser(userId)
return <div>{user?.name}</div>
}
// Incorrect: Class component
class UserProfile extends React.Component { /* ... */ }
```
**Composition Pattern**
```typescript
// Correct: Compose smaller components
function Card({ children }: { children: React.ReactNode }) {
return <div className="rounded-lg border p-4">{children}</div>
}
function CardHeader({ children }: { children: React.ReactNode }) {
return <div className="font-semibold">{children}</div>
}
// Usage
<Card>
<CardHeader>Title</CardHeader>
<p>Content</p>
</Card>
```
**Avoid Prop Drilling**
```typescript
// Incorrect: Passing props through many levels
<App user={user}>
<Layout user={user}>
<Sidebar user={user}>
<UserMenu user={user} />
</Sidebar>
</Layout>
</App>
// Correct: Use Context for shared state
const UserContext = createContext<User | null>(null)
function App() {
const user = useCurrentUser()
return (
<UserContext.Provider value={user}>
<Layout>
<Sidebar>
<UserMenu />
</Sidebar>
</Layout>
</UserContext.Provider>
)
}
```
---
## 2. Eliminating Waterfalls (CRITICAL)
### Quick Reference
- `async-defer-await` - Move await into branches where actually used
- `async-parallel` - Use Promise.all() for independent operations
- `async-dependencies` - Handle partial dependencies correctly
- `async-api-routes` - Start promises early, await late in API routes
- `async-suspense-boundaries` - Use Suspense to stream content
### Key Principles
Waterfalls are the #1 performance killer. Each sequential await adds full network latency.
**Parallel Data Fetching**
```typescript
// Incorrect: Sequential waterfalls
async function Page() {
const user = await fetchUser()
const posts = await fetchPosts()
const comments = await fetchComments()
return <div>{/* render */}</div>
}
// Correct: Parallel fetching
async function Page() {
const [user, posts, comments] = await Promise.all([
fetchUser(),
fetchPosts(),
fetchComments()
])
return <div>{/* render */}</div>
}
```
**Strategic Suspense Boundaries**
```typescript
// Stream content as it becomes available
function Page() {
return (
<div>
<Header />
<Suspense fallback={<PostsSkeleton />}>
<Posts />
</Suspense>
<Suspense fallback={<CommentsSkeleton />}>
<Comments />
</Suspense>
</div>
)
}
```
---
## 3. Bundle Size Optimization (CRITICAL)
### Quick Reference
- `bundle-barrel-imports` - Import directly, avoid barrel files
- `bundle-dynamic-imports` - Use next/dynamic for heavy components
- `bundle-defer-third-party` - Load analytics/logging after hydration
- `bundle-conditional` - Load modules only when feature is activated
- `bundle-preload` - Preload on hover/focus for perceived speed
### Key Principles
**Avoid Barrel File Imports**
```typescript
// Incorrect: Imports entire library
import { Button } from '@/components'
import { formatDate } from '@/utils'
// Correct: Direct imports enable tree-shaking
import { Button } from '@/components/ui/button'
import { formatDate } from '@/utils/date'
```
**Dynamic Imports**
```typescript
import dynamic from 'next/dynamic'
// Load only when needed
const HeavyChart = dynamic(() => import('./HeavyChart'), {
loading: () => <ChartSkeleton />,
ssr: false
})
function Dashboard({ showChart }) {
return showChart ? <HeavyChart /> : null
}
```
---
## 4. Server Components & Actions (HIGH)
### Quick Reference
- `server-default-server` - Components are Server Components by default
- `server-use-client-boundary` - Add 'use client' only when needed
- `server-actions` - Use Server Actions for mutations
- `server-cache-react` - Use React.cache() for per-request deduplication
- `server-serialization` - Minimize data passed to client components
### Key Principles
**Server Components by Default**
```typescript
// Server Component (default) - can be async
async function ProductPage({ id }: { id: string }) {
const product = await db.product.findUnique({ where: { id } })
return <ProductDetails product={product} />
}
// Client Component - only when needed for interactivity
'use client'
function AddToCartButton({ productId }: { productId: string }) {
const [isPending, startTransition] = useTransition()
return (
<Button
onClick={() => startTransition(() => addToCart(productId))}
disabled={isPending}
>
Add to Cart
</Button>
)
}
```
**Server Actions**
```typescript
// actions.ts
'use server'
export async function createPost(formData: FormData) {
const title = formData.get('title') as string
const content = formData.get('content') as string
await db.post.create({ data: { title, content } })
revalidatePath('/posts')
}
// Component usage
function CreatePostForm() {
return (
<form action={createPost}>
<Input name="title" placeholder="Title" />
<Textarea name="content" placeholder="Content" />
<Button type="submit">Create Post</Button>
</form>
)
}
```
---
## 5. shadcn/ui Patterns (HIGH)
### Quick Reference
- `shadcn-composition` - Build on existing shadcn/ui primitives
- `shadcn-variants` - Use class-variance-authority for component variants
- `shadcn-theme-integration` - Use CSS custom properties for theming
- `shadcn-accessibility` - Leverage built-in accessibility from Radix
- `shadcn-customization` - Modify copied components, don't wrap excessively
### Core Principles
shadcn/ui is built around:
- **Open Code**: Components are copied into your project, fully customizable
- **Composition**: Every component uses a common, composable interface
- **Beautiful Defaults**: Carefully chosen default styles
- **Accessibility by Default**: Built on Radix UI primitives
### Component Installation
```bash
# Add components as needed
npx shadcn@latest add button
npx shadcn@latest add card
npx shadcn@latest add dialog
npx shadcn@latest add form
```
### Building Custom Components
**Composition Over Creation**
```typescript
// Correct: Build on existing primitives
import { CardRelated 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.