Communitygithub.com

ComeOnOliver/skillshub

Next.js 16 缓存组件 - PPR、use cache 指令、cacheLife、cacheTag、updateTag

skillshub 是什么?

该技能文档涵盖了 Next.js 16+ 中的缓存组件(Cache Components),这是实现部分预渲染(PPR)的核心机制。它详细解释了如何在一个路由中混合静态内容、缓存内容和动态内容,从而优化页面加载性能。技能支持三种内容类型:静态(自动预渲染)、缓存(通过 `use cache` 指令)和动态(通过 Suspense 实现流式加载)。文档提供了从启用配置、使用 `cacheLife` 和 `cacheTag` 进行缓存生命周期管理和标签化,到缓存失效(包括 `updateTag` 和 `revalidateTag`)的完整指南。特别强调了 `use cache` 指令无法直接访问 `cookies()` 等运行时 API 的限制,并给出了传递参数或使用 `use cache: private` 的解决方案。该技能适用于 Next.js 应用开发者,帮助他们在 Node.js 运行时环境中高效管理缓存策略,并提供了从旧版本迁移的配置对照表。

兼容平台~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() - 后台重新验证

用于“过期-重新验证”模式:

'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 运行时 - 需要 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

相关技能