Communitygithub.com

Cache-Komponenten (Next.js 16+)

Aktiviert Partial Prerendering (PPR) und die `use cache`-Direktive in Next.js 16, um statische, gecachte und dynamische Inhalte innerhalb einer Route zu kombinieren.

Was ist Cache-Komponenten (Next.js 16+)?

Dieses Skill für Next.js 16+ führt Cache-Komponenten und das `use cache`-Direktiv ein, das `experimental.ppr` ersetzt. Es ermöglicht Partial Prerendering (PPR), bei dem Entwickler statische, gecachte und dynamische Inhalte mithilfe von Suspense in einer einzigen Route mischen können. Der Skill behandelt drei Inhaltstypen: statisch (zur Build-Zeit vorgerendert), gecacht (mit `use cache` und benutzerdefinierten Lebensdauern über `cacheLife()`) und dynamisch (in Suspense eingewickelt für Laufzeitaktualität). Er erklärt die Cache-Invalidierung über Tags mit `cacheTag()` und `revalidateTag()` sowie sofortige Aktualisierung mit `updateTag()`. Wichtigste Einschränkung: Innerhalb von `use cache` ist der Zugriff auf `cookies()`, `headers()` oder `searchParams` nicht erlaubt; diese müssen als Argumente übergeben werden. Der Skill enthält eine vollständige Migrationsanleitung von vorherigen Next.js-Versionen und Unterstützung für benutzerdefinierte Cache-Profile. Er wird für Entwickler empfohlen, die mit Next.js 16 arbeiten und performante Hybrid-Seiten mit optimiertem Caching erstellen möchten.

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

In Ihrer bevorzugten KI fragen

Öffnet einen neuen Chat, in dem dieser Agent-Skill bereits geladen ist.

Dokumentation

Was macht Cache-Komponenten (Next.js 16+)?

Cache-Komponenten ermöglichen Partial Prerendering (PPR) – statische, gecachte und dynamische Inhalte in einer einzigen Route.

Cache-Komponenten aktivieren

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

const nextConfig: NextConfig = {
  cacheComponents: true,
}

export default nextConfig

Dies ersetzt das alte experimental.ppr-Flag.


Drei Inhaltstypen

Mit aktivierten Cache-Komponenten fallen Inhalte in drei Kategorien:

1. Statisch (automatisch vorgerendert)

Synchroner Code, Importe, reine Berechnungen – werden zur Build-Zeit vorgerendert:

export default function Page() {
  return (
    <header>
      <h1>Unser Blog</h1>  {/* Statisch - sofort */}
      <nav>...</nav>
    </header>
  )
}

2. Gecacht (use cache)

Asynchrone Daten, die nicht bei jeder Anfrage neu geladen werden müssen:

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

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

3. Dynamisch (Suspense)

Laufzeitdaten, die aktuell sein müssen – in Suspense einwickeln:

import { Suspense } from 'react'

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

      <Suspense fallback={<p>Lade...</p>}>
        <UserPreferences />  {/* Dynamisch - streamt ein */}
      </Suspense>
    </>
  )
}

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

use cache-Direktiv

Dateiebene

'use cache'

export default async function Page() {
  // Ganze Seite wird gecacht
  const data = await fetchData()
  return <div>{data}</div>
}

Komponentenebene

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

Funktionsebene

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

Cache-Profile

Integrierte Profile

'use cache'                    // Standard: 5 Min veraltet, 15 Min Neuvalidierung
'use cache: remote'           // Plattform-eigener Cache (Redis, KV)
'use cache: private'          // Für Compliance, erlaubt Laufzeit-APIs

cacheLife() - Benutzerdefinierte Lebensdauer

import { cacheLife } from 'next/cache'

async function getData() {
  'use cache'
  cacheLife('hours')  // Integriertes Profil
  return fetch('/api/data')
}

Integrierte Profile: 'default', 'minutes', 'hours', 'days', 'weeks', 'max'

Inline-Konfiguration

async function getData() {
  'use cache'
  cacheLife({
    stale: 3600,      // 1 Stunde – veraltet bedienen während Neuvalidierung
    revalidate: 7200, // 2 Stunden – Hintergrund-Neuvalidierungsintervall
    expire: 86400,    // 1 Tag – harte Ablaufzeit
  })
  return fetch('/api/data')
}

Cache-Invalidierung

cacheTag() - Gecachten Inhalt markieren

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() - Sofortige Invalidierung

Verwenden, wenn der Cache innerhalb derselben Anfrage aktualisiert werden muss:

'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}`)  // Sofortige Aktualisierung – dieselbe Anfrage sieht neue Daten
}

revalidateTag() - Hintergrund-Neuvalidierung

Verwenden für das stale-while-revalidate-Verhalten:

'use server'

import { revalidateTag } from 'next/cache'

export async function createPost(data: FormData) {
  await db.posts.create({ data })
  revalidateTag('posts')  // Hintergrund – nächste Anfrage sieht neue Daten
}

Einschränkung bei Laufzeitdaten

Innerhalb von use cache darf nicht auf cookies(), headers() oder searchParams zugegriffen werden.

Lösung: Als Argumente übergeben

// Falsch – Laufzeit-API innerhalb von use cache
async function CachedProfile() {
  'use cache'
  const session = (await cookies()).get('session')?.value  // Fehler!
  return <div>{session}</div>
}

// Richtig – außerhalb extrahieren, als Argument übergeben
async function ProfilePage() {
  const session = (await cookies()).get('session')?.value
  return <CachedProfile sessionId={session} />
}

async function CachedProfile({ sessionId }: { sessionId: string }) {
  'use cache'
  // sessionId wird automatisch Teil des Cache-Schlüssels
  const data = await fetchUserData(sessionId)
  return <div>{data.name}</div>
}

Ausnahme: use cache: private

Für Compliance-Anforderungen, wenn ein Refactoring nicht möglich ist:

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

Cache-Schlüsselgenerierung

Cache-Schlüssel werden automatisch basierend auf folgenden Faktoren erstellt:

  • Build-ID – macht alle Caches bei einem Deployment ungültig
  • Funktions-ID – Hash des Funktionsspeicherorts
  • Serialisierbare Argumente – Props werden Teil des Schlüssels
  • Closure-Variablen – Werte aus dem äußeren Gültigkeitsbereich werden einbezogen
async function Component({ userId }: { userId: string }) {
  const getData = async (filter: string) => {
    'use cache'
    // Cache-Schlüssel = userId (Closure) + filter (Argument)
    return fetch(`/api/users/${userId}?filter=${filter}`)
  }
  return getData('active')
}

Vollständiges Beispiel

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

export default function DashboardPage() {
  return (
    <>
      {/* Statisches Grundgerüst – sofort vom CDN */}
      <header><h1>Dashboard</h1></header>
      <nav>...</nav>

      {/* Gecacht – schnell, stündlich neu validiert */}
      <Stats />

      {/* Dynamisch – streamt mit aktuellen Daten ein */}
      <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} />
}

Migration von früheren Versionen

Alte KonfigurationErsatz
experimental.pprcacheComponents: true
dynamic = 'force-dynamic'Entfernen (Standardverhalten)
dynamic = 'force-static''use cache' + cacheLife('max')
revalidate = NcacheLife({ revalidate: N })
unstable_cache()'use cache'-Direktiv

Einschränkungen

  • Edge-Laufzeit nicht unterstützt – Node.js erforderlich
  • Statischer Export nicht unterstützt – Server erforderlich
  • Nicht-deterministische Werte (Math.random(), Date.now()) werden innerhalb von use cache nur einmal zur Build-Zeit ausgeführt

Für Laufzeit-Zufall außerhalb des Caches:

import { connection } from 'next/server'

async function DynamicContent() {
  await connection()  // Zur Anfragezeit verschieben
  const id = crypto.randomUUID()  // Unterschiedlich pro Anfrage
  return <div>{id}</div>
}

Quellen:

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

Verwandte Skills