Claude
Skills
Sign in
Back

react-best-practices

Included with Lifetime
$97 forever

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.

Design

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 { Card

Related in Design