Next.js Best Practices
Principles for Next.js App Router development.
1. Server vs Client Components
| Feature | Server Component (Default) | Client Component ('use client') |
|---|---|---|
| Data Fetching | Direct (Async/Await) | via Hooks (SWR/React Query) |
| Interactivity | ❌ No | ✅ Yes (useState, onClick) |
| Browser APIs | ❌ No | ✅ Yes (window, document) |
| Performance | ✅ Better (Less JS) | ❌ Larger bundle |
2. Data Fetching
- •Fetch data in Server Components where possible.
- •Use
fetchwith Next.js specific caching options (no-store,revalidate). - •Pass data down as props to Client Components.
3. Server Actions
- •Use Server Actions for data mutations (forms, button clicks).
- •Keep them in
src/actions/or alongside the component with'use server'. - •Handle loading states with
useFormStatusoruseTransition.
4. API Routes
- •Use
app/api/for external access or complex webhooks. - •Use Zod for type-safe validation.
- •Return standard HTTP status codes.