Communitygithub.com

ComeOnOliver/skillshub

Next.js 16 キャッシュコンポーネント — PPR、use cache ディレクティブ、cacheLife、cacheTag、updateTag を解説します。

skillshub とは?

このスキルは、Next.js 16 で導入されたキャッシュコンポーネント(Cache Components)について詳しく解説します。Partial Prerendering(PPR)を実現し、同一ルート内で静的コンテンツ、キャッシュされたコンテンツ、動的コンテンツを自由に組み合わせられます。'use cache' ディレクティブによるファイル・コンポーネント・関数単位のキャッシュ制御、cacheLife による細かい有効期間設定、cacheTag と updateTag/revalidateTag によるキャッシュの即時・バックグラウンド無効化方法をカバー。また、cookies/headers といったランタイム API の制約とその回避策(引数渡しや 'use cache: private' の利用)も説明します。Next.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に質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

キャッシュコンポーネント(Next.js 16+)

キャッシュコンポーネントは、Partial Prerendering (PPR) を実現します。単一のルート内で静的、キャッシュ済み、動的なコンテンツを混在させることができます。

キャッシュコンポーネントの有効化

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

const nextConfig: NextConfig = {
  cacheComponents: true,
}

export default nextConfig

これは古い experimental.ppr フラグを置き換えます。


3つのコンテンツタイプ

キャッシュコンポーネントを有効にすると、コンテンツは次の3つのカテゴリに分類されます。

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分 stale、15分 revalidate
'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時間 - stale のまま再検証中も配信
    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>

      {/* キャッシュ済み - 高速、1時間ごとに再検証 */}
      <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 内でビルド時に1回だけ実行される

キャッシュ外でリクエスト時にランダム性が必要な場合:

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

関連スキル