2.7 KiB
2.7 KiB
name, description
| name | description |
|---|---|
| nextjs-app-router-patterns | Best practices and patterns for building applications with Next.js App Router (v13+). |
Next.js App Router Patterns
Core Principles
Server-First by Default
- Use Server Components for everything possible (data fetching, layout, static content).
- Use Client Components (
"use client") only when interactivity (hooks, event listeners) is needed. - Pass Data Down: Fetch data in Server Components and pass it as props to Client Components.
- Composition: Wrap Client Components around Server Components to avoid "rendering undefined" issues or waterfall de-opts.
Routing & Layouts
- File Structure:
page.tsx: Route UI.layout.tsx: Shared UI (wraps pages).loading.tsx: Loading state (Suspense).error.tsx: Error boundary.not-found.tsx: 404 UI.template.tsx: Layout that re-mounts on navigation.
- Parallel Routes: Use
@folderfor parallel UI (e.g. dashboards). - Intercepting Routes: Use
(..)to intercept navigation (e.g. modals). - Route Groups: Use
(group)to organize routes without affecting the URL path.
Data Fetching Patterns
Server Side
- Direct Async/Await:
const data = await fetch(...)inside the component. - Request Memoization:
fetchis automatically memoized. For DB calls, useReact.cache. - Data Caching:
fetch(url, { next: { revalidate: 3600 } })for ISR.fetch(url, { cache: 'no-store' })for SSR.- Use
unstable_cachefor caching DB results.
Client Side
- Use SWR or TanStack Query for client-side fetching.
- Avoid
useEffectfor data fetching to prevent waterfalls. - Prefetch data using
queryClient.prefetchQueryin Server Components and hydrate on client.
Server Actions
- Use Server Actions (
"use server") for mutations (form submissions, button clicks). - Define actions in separate files (e.g.
actions.ts) for better organization and security. - Use
useFormState(oruseActionStatein React 19) to handle loading/error states.
Optimization
- Images: Use
next/imagefor automatic resizing and format conversion. - Fonts: Use
next/fontto eliminate layout shift (CLS). - Scripts: Use
next/scriptwithstrategy="afterInteractive". - Streaming: Use
<Suspense>to stream parts of the UI (e.g. slow data fetches).
Common Anti-Patterns to Avoid
- Fetching in Client Components without cache lib: Leads to waterfalls.
- "use client" at top level layout: Forces the entire tree to be client-side.
- Prop Drilling: specialized
Contextshould be used sparingly; prefer Composition. - Large Barrel Files: Avoid
index.tsexporting everything; import directly to aid tree-shaking.