Communitygithub.com

ComeOnOliver/skillshub

Next.js 16 快取元件 - PPR、use cache 指令、cacheLife、cacheTag、updateTag

skillshub 是什麼?

這個技能專注於 Next.js 16 以上的「快取元件」(Cache Components),這是實現部分預先渲染(Partial Prerendering, PPR)的核心機制。它允許開發者在同一個路由中混合靜態、快取和動態內容,從而大幅提升頁面載入速度與使用者體驗。技能詳細說明了如何透過 `cacheComponents: true` 啟用此功能,並深入介紹了三種內容類型:靜態(自動預先渲染)、快取(使用 `use cache` 指令)和動態(搭配 Suspense)。此外,它還涵蓋了進階的快取管理工具,例如 `cacheLife()` 用於自訂快取生命週期、`cacheTag()` 用於標記快取內容,以及 `updateTag()` 和 `revalidateTag()` 用於即時或背景快取失效。此技能也說明了 `use cache` 區塊內無法直接存取 `cookies()` 或 `headers()` 等執行時期 API 的限制,並提供了解決方案,例如將值作為參數傳入或使用 `use cache: private` 設定檔。整體而言,這份指南幫助開發者全面掌握 Next.js 16 中高效、細粒度的快取策略,以建構更快速、更具回應性的應用程式。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/ComeOnOliver/skillshub/tree/HEAD/skills/aiskillstore/marketplace/vercel-labs/next-cache-components

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

快取元件 (Next.js 16+)

快取元件能實現部分預先渲染 (PPR) — 在同一路由中混合靜態、快取和動態內容。

啟用快取元件

// next.config.ts
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  cacheComponents: true,
}

export default nextConfig

這取代了舊的 experimental.ppr 旗標。


三種內容類型

啟用快取元件後,內容分為三類:

1. 靜態 (自動預先渲染)

同步程式碼、匯入、純計算 — 在建置時預先渲染:

export default function Page() {
  return (
    <header>
      <h1>我們的部落格</h1>  {/* 靜態 - 即時 */}
      <nav>...</nav>
    </header>
  )
}

2. 快取 (use cache)

不需要每次請求都重新擷取的非同步資料:

async function BlogPosts() {
  'use cache'
  cacheLife('hours')

  const posts = await db.posts.findMany()
  return <PostList posts={posts} />
}

3. 動態 (Suspense)

必須維持新鮮的執行時期資料 — 包裹在 Suspense 中:

import { Suspense } from 'react'

export default function Page() {
  return (
    <>
      <BlogPosts />  {/* 快取 */}

      <Suspense fallback={<p>載入中...</p>}>
        <UserPreferences />  {/* 動態 - 串流傳入 */}
      </Suspense>
    </>
  )
}

async function UserPreferences() {
  const theme = (await cookies()).get('theme')?.value
  return <p>主題: {theme}</p>
}

use cache 指令

檔案層級

'use cache'

export default async function Page() {
  // 整個頁面被快取
  const data = await fetchData()
  return <div>{data}</div>
}

元件層級

export async function CachedComponent() {
  'use cache'
  const data = await fetchData()
  return <div>{data}</div>
}

函式層級

export async function getData() {
  'use cache'
  return db.query('SELECT * FROM posts')
}

快取設定檔

內建設定檔

'use cache'                    // 預設: 5 分鐘過期,15 分鐘重新驗證
'use cache: remote'           // 平台提供的快取 (Redis, KV)
'use cache: private'          // 用於合規,允許使用執行時期 API

cacheLife() - 自訂生命週期

import { cacheLife } from 'next/cache'

async function getData() {
  'use cache'
  cacheLife('hours')  // 內建設定檔
  return fetch('/api/data')
}

內建設定檔:'default', 'minutes', 'hours', 'days', 'weeks', 'max'

內嵌設定

async function getData() {
  'use cache'
  cacheLife({
    stale: 3600,      // 1 小時 - 在重新驗證期間提供過期內容
    revalidate: 7200, // 2 小時 - 背景重新驗證間隔
    expire: 86400,    // 1 天 - 強制過期
  })
  return fetch('/api/data')
}

快取失效

cacheTag() - 標記快取內容

import { cacheTag } from 'next/cache'

async function getProducts() {
  'use cache'
  cacheTag('products')
  return db.products.findMany()
}

async function getProduct(id: string) {
  'use cache'
  cacheTag('products', `product-${id}`)
  return db.products.findUnique({ where: { id } })
}

updateTag() - 即時失效

當你需要在同一個請求內重新整理快取時使用:

'use server'

import { updateTag } from 'next/cache'

export async function updateProduct(id: string, data: FormData) {
  await db.products.update({ where: { id }, data })
  updateTag(`product-${id}`)  // 即時 - 同一個請求看到最新資料
}

revalidateTag() - 背景重新驗證

用於「過期時重新驗證」(stale-while-revalidate)行為:

'use server'

import { revalidateTag } from 'next/cache'

export async function createPost(data: FormData) {
  await db.posts.create({ data })
  revalidateTag('posts')  // 背景 - 下一個請求看到最新資料
}

執行時期資料限制

在 use cache 內部無法存取 cookies()、headers() 或 searchParams。

解決方案:作為引數傳入

// 錯誤 - 在 use cache 內使用執行時期 API
async function CachedProfile() {
  'use cache'
  const session = (await cookies()).get('session')?.value  // 錯誤!
  return <div>{session}</div>
}

// 正確 - 在外部提取,作為引數傳入
async function ProfilePage() {
  const session = (await cookies()).get('session')?.value
  return <CachedProfile sessionId={session} />
}

async function CachedProfile({ sessionId }: { sessionId: string }) {
  'use cache'
  // sessionId 會自動成為快取鍵的一部分
  const data = await fetchUserData(sessionId)
  return <div>{data.name}</div>
}

例外情況:use cache: private

用於無法重構程式碼的合規需求:

async function getData() {
  'use cache: private'
  const session = (await cookies()).get('session')?.value  // 允許
  return fetchData(session)
}

快取鍵產生

快取鍵會自動根據以下項目產生:

  • 建置 ID - 部署時使所有快取失效
  • 函式 ID - 函式位置的雜湊值
  • 可序列化的引數 - props 成為鍵的一部分
  • 閉包變數 - 包含外部作用域的值
async function Component({ userId }: { userId: string }) {
  const getData = async (filter: string) => {
    'use cache'
    // 快取鍵 = userId (閉包) + filter (引數)
    return fetch(`/api/users/${userId}?filter=${filter}`)
  }
  return getData('active')
}

完整範例

import { Suspense } from 'react'
import { cookies } from 'next/headers'
import { cacheLife, cacheTag } from 'next/cache'

export default function DashboardPage() {
  return (
    <>
      {/* 靜態外殼 - 從 CDN 即時取得 */}
      <header><h1>儀表板</h1></header>
      <nav>...</nav>

      {/* 快取 - 快速,每小時重新驗證 */}
      <Stats />

      {/* 動態 - 使用最新資料串流傳入 */}
      <Suspense fallback={<NotificationsSkeleton />}>
        <Notifications />
      </Suspense>
    </>
  )
}

async function Stats() {
  'use cache'
  cacheLife('hours')
  cacheTag('dashboard-stats')

  const stats = await db.stats.aggregate()
  return <StatsDisplay stats={stats} />
}

async function Notifications() {
  const userId = (await cookies()).get('userId')?.value
  const notifications = await db.notifications.findMany({
    where: { userId, read: false }
  })
  return <NotificationList items={notifications} />
}

從先前版本遷移

舊設定取代方案
experimental.pprcacheComponents: true
dynamic = 'force-dynamic'移除 (預設行為)
dynamic = 'force-static''use cache' + cacheLife('max')
revalidate = NcacheLife({ revalidate: N })
unstable_cache()'use cache' 指令

限制

  • 不支援 Edge runtime - 需要 Node.js
  • 不支援靜態匯出 - 需要伺服器
  • 非確定性值 (Math.random(), Date.now()) 在 use cache 內部僅在建置時執行一次

若需要在快取外部取得請求時間的隨機值:

import { connection } from 'next/server'

async function DynamicContent() {
  await connection()  // 延遲到請求時間執行
  const id = crypto.randomUUID()  // 每個請求不同
  return <div>{id}</div>
}

來源:

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

ComeOnOliver/skillshub

Create stunning, animation-rich HTML presentations from scratch or by converting PowerPoint files. Use when the user wants to build a presentation, convert a PPT/PPTX to web, or create slides for a talk/pitch. Helps non-designers discover their aesthetic through visual exploration rather than abstract choices.

ComeOnOliver/skillshub

Next.js 16+ 和 Turbopack — 增量打包、文件系统缓存、开发速度,以及何时使用 Turbopack 与 webpack。

ComeOnOliver/skillshub

SwiftUI architecture patterns, state management with @Observable, view composition, navigation, performance optimization, and modern iOS/macOS UI best practices.

ComeOnOliver/skillshub

See, Understand, Act on video and audio. See- ingest from local files, URLs, RTSP/live feeds, or live record desktop; return realtime context and playable stream links. Understand- extract frames, build visual/semantic/temporal indexes, and search moments with timestamps and auto-clips. Act- transcode and normalize (codec, fps, resolution, aspect ratio), perform timeline edits (subtitles, text/image overlays, branding, audio overlays, dubbing, translation), generate media assets (image, audio, video), and create real time alerts for events from live streams or desktop capture.

ComeOnOliver/skillshub

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

ComeOnOliver/skillshub

Next.js 15 애플리케이션을 위한 프론트엔드 개발 가이드라인. React 19, TypeScript, Shadcn/ui, Tailwind CSS를 사용한 모던 패턴. Server Components, Client Components, App Router, 파일 구조, Shadcn/ui 컴포넌트, 성능 최적화, TypeScript 모범 사례 포함. 컴포넌트, 페이지, 기능 생성, 데이터 페칭, 스타일링, 라우팅, 프론트엔드 코드 작업 시 사용.

ComeOnOliver/skillshub

Provides Tamagui patterns for config v4, compiler optimization, styled context, and cross-platform styling. Must use when working with Tamagui projects (tamagui.config.ts, @tamagui imports).

ComeOnOliver/skillshub

Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.

ComeOnOliver/skillshub

Create high-converting, visually distinctive landing pages. Use when building marketing pages, product launches, SaaS homepages, or any single-page conversion-focused website. Guides section-by-section composition with anti-AI-slop principles.

ComeOnOliver/skillshub

Auto-loaded context for Portfolio Buddy 2 development. Use for ANY task involving: React 19 development, TypeScript, portfolio analysis features, metrics calculations, trading strategy comparison, or working with the Portfolio Buddy 2 codebase. Contains tech stack, known issues, and architectural constraints.

ComeOnOliver/skillshub

Next.js development tooling via MCP. Inspect routes, components, build info, and debug Next.js apps. Use when working on Next.js applications, debugging routing, or inspecting app structure. NOT for general React or non-Next.js projects.

ComeOnOliver/skillshub

Implement UI using Shadcn MCP (atoms/theme) and 21st.dev MCP (complex sections). Use when adding buttons, layouts, or generating landing pages.

ComeOnOliver/skillshub

A conceptual skill for building an API client in Next.js that handles JWT tokens

ComeOnOliver/skillshub

Best practices and patterns for Next.js App Router, Server Actions, and Routing in this project.

ComeOnOliver/skillshub

The Design System, Theme, and UX rules for the Physical AI Hub.

ComeOnOliver/skillshub

Comprehensive frontend development skill for building modern, performant web applications using ReactJS, NextJS, TypeScript, Tailwind CSS. Includes component scaffolding, performance optimization, bundle analysis, and UI best practices. Use when developing frontend features, optimizing performance, implementing UI/UX designs, managing state, or reviewing frontend code.

ComeOnOliver/skillshub

This document captures learnings from fixing keyboard navigation issues when floating components (Select, DropdownMenu, Popover) have CSS open/close animations.

ComeOnOliver/skillshub

Build Next.js 16 applications with correct patterns and distinctive design. Use when creating pages, layouts, dynamic routes, upgrading from Next.js 15, or implementing proxy.ts. Covers breaking changes (async params/searchParams, Turbopack, cacheComponents) and frontend aesthetics. NOT when building non-React or backend-only applications.

ComeOnOliver/skillshub

Comprehensive Framer Motion animation library for React. Covers motion components, variants, gestures, page transitions, and scroll animations. Use when adding animations to React/Next.js applications.

ComeOnOliver/skillshub

Build interfaces that resonate, not just render. This skill enforces bold, intentional

相關技能