← 返回
未分类 中文

Next.js 15 Best Practices

Apply Next.js 15 best practices and modern patterns including App Router, Server Components, Server Actions, caching strategies, and performance optimization...
运用 Next.js 15 最佳实践和现代模式,包括 App Router、服务器组件、服务器操作、缓存策略及性能优化。
goldath goldath 来源
未分类 clawhub v1.0.0 1 版本 100000 Key: 无需
★ 0
Stars
📥 504
下载
💾 1
安装
1
版本
#latest

概述

Next.js 15 Best Practices

Core Principles

  1. Default to Server Components — only add "use client" when you need interactivity or browser APIs
  2. Colocate by feature — keep components, hooks, and utils near the routes that use them
  3. Type everything — leverage TypeScript with strict mode enabled
  4. Cache deliberately — understand the four caching layers and opt in/out explicitly

Project Structure

app/
  (marketing)/        # route group: no URL segment
    page.tsx
  (dashboard)/
    layout.tsx
    [id]/
      page.tsx
  api/
    route.ts
components/
  ui/                 # shared, "dumb" UI components
  features/           # feature-specific components
lib/
  db.ts               # database client (singleton)
  auth.ts             # auth helpers
  utils.ts

Server vs. Client Components

// ✅ Server Component (default) — runs on server, no JS sent to client
export default async function ProductList() {
  const products = await db.product.findMany()
  return <ul>{products.map(p => <li key={p.id}>{p.name}</li>)}</ul>
}

// ✅ Client Component — only when needed
"use client"
import { useState } from "react"
export function Counter() {
  const [n, setN] = useState(0)
  return <button onClick={() => setN(n + 1)}>{n}</button>
}

Data Fetching Patterns

// Parallel fetching (avoid sequential waterfalls)
export default async function Dashboard() {
  const [user, stats] = await Promise.all([
    fetchUser(),
    fetchStats(),
  ])
  return <View user={user} stats={stats} />
}

// fetch with cache control
const data = await fetch("https://api.example.com/data", {
  next: { revalidate: 60 },   // ISR: revalidate every 60s
  // cache: "no-store"         // always fresh
  // cache: "force-cache"      // static, until manual revalidation
})

Server Actions

// app/actions.ts
"use server"
import { revalidatePath } from "next/cache"

export async function createPost(formData: FormData) {
  const title = formData.get("title") as string
  await db.post.create({ data: { title } })
  revalidatePath("/posts")
}

// app/posts/new/page.tsx
import { createPost } from "../actions"
export default function NewPost() {
  return (
    <form action={createPost}>
      <input name="title" />
      <button type="submit">Create</button>
    </form>
  )
}

Metadata & SEO

// Static metadata
export const metadata = {
  title: "My App",
  description: "...",
}

// Dynamic metadata
export async function generateMetadata({ params }) {
  const post = await fetchPost(params.slug)
  return { title: post.title, description: post.excerpt }
}

Error & Loading States

// app/posts/loading.tsx  — automatic Suspense boundary
export default function Loading() {
  return <Skeleton />
}

// app/posts/error.tsx  — automatic error boundary
"use client"
export default function Error({ error, reset }) {
  return <button onClick={reset}>Retry: {error.message}</button>
}

Performance Checklist

  • [ ] Images use next/image with explicit width/height
  • [ ] Fonts use next/font (zero layout shift)
  • [ ] Dynamic imports for heavy client components: dynamic(() => import(...))
  • [ ] generateStaticParams for known dynamic routes
  • [ ] Bundle analyzer run: ANALYZE=true next build
  • [ ] Partial Prerendering (PPR) considered for mixed static/dynamic pages

References

See references/ folder for routing patterns, caching deep-dive, and migration guide.

版本历史

共 1 个版本

  • v1.0.0 当前
    2026-05-03 08:35 安全 安全

安全检测

腾讯云安全 (Keen)

安全,无风险
查看报告

腾讯云安全 (Sanbu)

安全,无风险
查看报告

🔗 相关推荐

office-efficiency

中文周报日报自动生成

goldath
自动从要点输入生成专业的周/日工作报告。适用于需要将原始任务笔记整理成精炼的周报/日报的场景。
★ 0 📥 565
dev-programming

Github

steipete
使用 `gh` CLI 与 GitHub 交互,通过 `gh issue`、`gh pr`、`gh run` 和 `gh api` 管理议题、PR、CI 运行及高级查询。
★ 677 📥 326,913
dev-programming

CodeConductor.ai

larsonreever
AI驱动平台,提供快速全栈开发、智能体、工作流自动化及低代码AI集成的可扩展产品创建。
★ 72 📥 181,709