Communitygithub.com

Composants de Cache (Next.js 16+)

Activez le rendu partiel (PPR) en mélangeant contenu statique, en cache et dynamique dans une seule route avec la directive 'use cache', cacheLife, cacheTag et updateTag.

Qu'est-ce que Composants de Cache (Next.js 16+) ?

Cette compétence permet aux développeurs de tirer parti des composants de cache introduits dans Next.js 16 pour la génération partielle de pages (PPR). Elle explique comment configurer le cache via le fichier `next.config.ts` avec l'option `cacheComponents: true`, remplaçant l'ancien flag `experimental.ppr`. Le contenu d'une route est alors classé en trois types : statique (prérendu à la compilation), mis en cache via la directive `'use cache'` (avec des profils de durée de vie comme `cacheLife`) et dynamique (enveloppé dans Suspense pour un rafraîchissement en temps réel). La compétence détaille également l'invalidation du cache avec `cacheTag` et `updateTag`, ainsi que les contraintes d'exécution (comme l'accès à `cookies()` réservé au code dynamique). Enfin, elle fournit un tableau de migration depuis les versions antérieures et les limitations actuelles (pas de support Edge Runtime ni d'export statique).

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

Demander à votre IA préférée

Ouvre une nouvelle conversation avec cette compétence d'agent déjà préchargée.

Documentation

Que fait Composants de Cache (Next.js 16+) ?

Les composants de cache permettent le rendu partiel (PPR) - mélanger contenu statique, en cache et dynamique dans une seule route.

Activer les composants de cache

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

const nextConfig: NextConfig = {
  cacheComponents: true,
}

export default nextConfig

Ceci remplace l'ancien flag experimental.ppr.


Trois types de contenu

Avec les composants de cache activés, le contenu se répartit en trois catégories :

1. Statique (prérendu automatiquement)

Code synchrone, imports, calculs purs - prérendu à la compilation :

export default function Page() {
  return (
    <header>
      <h1>Notre Blog</h1>  {/* Statique - instantané */}
      <nav>...</nav>
    </header>
  )
}

2. En cache (use cache)

Données asynchrones qui n'ont pas besoin d'être récupérées à chaque requête :

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

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

3. Dynamique (Suspense)

Données d'exécution qui doivent être fraîches - enveloppez-les dans Suspense :

import { Suspense } from 'react'

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

      <Suspense fallback={<p>Chargement...</p>}>
        <UserPreferences />  {/* Dynamique - diffusé en continu */}
      </Suspense>
    </>
  )
}

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

Directive use cache

Au niveau du fichier

'use cache'

export default async function Page() {
  // La page entière est mise en cache
  const data = await fetchData()
  return <div>{data}</div>
}

Au niveau du composant

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

Au niveau de la fonction

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

Profils de cache

Profils intégrés

'use cache'                    // Par défaut : 5min obsolète, 15min revalidation
'use cache: remote'           // Cache fourni par la plateforme (Redis, KV)
'use cache: private'          // Pour la conformité, autorise les API d'exécution

cacheLife() - Durée de vie personnalisée

import { cacheLife } from 'next/cache'

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

Profils intégrés : 'default', 'minutes', 'hours', 'days', 'weeks', 'max'

Configuration inline

async function getData() {
  'use cache'
  cacheLife({
    stale: 3600,      // 1 heure - servir obsolète pendant la revalidation
    revalidate: 7200, // 2 heures - intervalle de revalidation en arrière-plan
    expire: 86400,    // 1 jour - expiration dure
  })
  return fetch('/api/data')
}

Invalidation du cache

cacheTag() - Marquer le contenu mis en cache

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() - Invalidation immédiate

À utiliser lorsque vous avez besoin que le cache soit rafraîchi dans la même requête :

'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}`)  // Immédiat - la même requête voit les données fraîches
}

revalidateTag() - Revalidation en arrière-plan

À utiliser pour le comportement stale-while-revalidate :

'use server'

import { revalidateTag } from 'next/cache'

export async function createPost(data: FormData) {
  await db.posts.create({ data })
  revalidateTag('posts')  // Arrière-plan - la prochaine requête voit les données fraîches
}

Contrainte des données d'exécution

Impossible d'accéder à cookies(), headers() ou searchParams à l'intérieur de use cache.

Solution : passer en tant qu'arguments

// Erroné - API d'exécution dans use cache
async function CachedProfile() {
  'use cache'
  const session = (await cookies()).get('session')?.value  // Erreur !
  return <div>{session}</div>
}

// Correct - extraire en dehors, passer en argument
async function ProfilePage() {
  const session = (await cookies()).get('session')?.value
  return <CachedProfile sessionId={session} />
}

async function CachedProfile({ sessionId }: { sessionId: string }) {
  'use cache'
  // sessionId devient automatiquement partie de la clé de cache
  const data = await fetchUserData(sessionId)
  return <div>{data.name}</div>
}

Exception : use cache: private

Pour les besoins de conformité lorsque vous ne pouvez pas refactoriser :

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

Génération de la clé de cache

Les clés de cache sont automatiques basées sur :

  • ID de build - invalide tous les caches au déploiement
  • ID de fonction - hachage de l'emplacement de la fonction
  • Arguments sérialisables - les props deviennent partie de la clé
  • Variables de fermeture - les valeurs de la portée externe incluses
async function Component({ userId }: { userId: string }) {
  const getData = async (filter: string) => {
    'use cache'
    // Clé de cache = userId (fermeture) + filter (argument)
    return fetch(`/api/users/${userId}?filter=${filter}`)
  }
  return getData('active')
}

Exemple complet

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

export default function DashboardPage() {
  return (
    <>
      {/* Coque statique - instantané depuis le CDN */}
      <header><h1>Tableau de bord</h1></header>
      <nav>...</nav>

      {/* En cache - rapide, revalidation toutes les heures */}
      <Stats />

      {/* Dynamique - diffusé en continu avec des données fraîches */}
      <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 depuis les versions précédentes

Ancienne configurationRemplacement
experimental.pprcacheComponents: true
dynamic = 'force-dynamic'Supprimer (comportement par défaut)
dynamic = 'force-static''use cache' + cacheLife('max')
revalidate = NcacheLife({ revalidate: N })
unstable_cache()Directive 'use cache'

Limitations

  • Edge runtime non supporté - nécessite Node.js
  • Export statique non supporté - nécessite un serveur
  • Valeurs non déterministes (Math.random(), Date.now()) exécutées une fois à la compilation dans use cache

Pour l'aléatoire au moment de la requête en dehors du cache :

import { connection } from 'next/server'

async function DynamicContent() {
  await connection()  // Reporter au moment de la requête
  const id = crypto.randomUUID()  // Différent par requête
  return <div>{id}</div>
}

Sources :

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

Skills associés