Communitygithub.com

Componentes de caché (Next.js 16)

Componentes de caché que habilitan el prerenderizado parcial (PPR) para mezclar contenido estático, en caché y dinámico en una sola ruta.

¿Qué es Componentes de caché (Next.js 16)?

Este skill para Next.js 16+ introduce los Componentes de Caché, una característica que reemplaza el antiguo flag experimental `ppr` y permite Prerenderizado Parcial (PPR). Con `cacheComponents: true` en la configuración, los desarrolladores pueden mezclar sin problemas contenido estático, en caché y dinámico dentro de una misma ruta. La directiva `'use cache'` permite almacenar en caché páginas completas, componentes o funciones, y se puede personalizar su comportamiento mediante `cacheLife()` para definir tiempos de frescura y expiración. La invalidación de caché se maneja con `cacheTag()`, `revalidateTag()` (revalidación en segundo plano) y `updateTag()` (invalidación inmediata dentro de la misma solicitud). Una restricción importante es que dentro de `'use cache'` no se puede acceder a `cookies()`, `headers()` o `searchParams`; estos deben pasarse como argumentos. El skill también incluye una guía de migración desde versiones anteriores y cubre limitaciones como la falta de soporte para Edge Runtime y exportaciones estáticas. Es compatible con proyectos Next.js que usen Node.js y estén en la versión 16 o superior.

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

Preguntar en tu IA favorita

Abre un nuevo chat con esta habilidad de agente ya precargada.

Documentación

Componentes de Caché (Next.js 16+)

Los Componentes de Caché permiten el Prerenderizado Parcial (PPR): mezclar contenido estático, en caché y dinámico en una sola ruta.

Habilitar Componentes de Caché

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

const nextConfig: NextConfig = {
  cacheComponents: true,
}

export default nextConfig

Esto reemplaza el antiguo flag experimental.ppr.


Tres Tipos de Contenido

Con los Componentes de Caché habilitados, el contenido se divide en tres categorías:

1. Estático (Pre-renderizado automáticamente)

Código síncrono, importaciones, cálculos puros: pre-renderizados en tiempo de compilación:

export default function Page() {
  return (
    <header>
      <h1>Nuestro Blog</h1>  {/* Estático - instantáneo */}
      <nav>...</nav>
    </header>
  )
}

2. En Caché (use cache)

Datos asíncronos que no necesitan búsquedas frescas en cada solicitud:

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

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

3. Dinámico (Suspense)

Datos en tiempo de ejecución que deben estar frescos: envuélvelos en Suspense:

import { Suspense } from 'react'

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

      <Suspense fallback={<p>Cargando...</p>}>
        <UserPreferences />  {/* Dinámico - se transmite */}
      </Suspense>
    </>
  )
}

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

Directiva use cache

A Nivel de Archivo

'use cache'

export default async function Page() {
  // Toda la página se almacena en caché
  const data = await fetchData()
  return <div>{data}</div>
}

A Nivel de Componente

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

A Nivel de Función

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

Perfiles de Caché

Perfiles Incorporados

'use cache'                    // Por defecto: 5m obsoleto, 15m revalidación
'use cache: remote'           // Caché proporcionado por la plataforma (Redis, KV)
'use cache: private'          // Para cumplimiento, permite APIs de tiempo de ejecución

cacheLife() - Vida Útil Personalizada

import { cacheLife } from 'next/cache'

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

Perfiles incorporados: 'default', 'minutes', 'hours', 'days', 'weeks', 'max'

Configuración en Línea

async function getData() {
  'use cache'
  cacheLife({
    stale: 3600,      // 1 hora - servir obsoleto mientras se revalida
    revalidate: 7200, // 2 horas - intervalo de revalidación en segundo plano
    expire: 86400,    // 1 día - expiración forzosa
  })
  return fetch('/api/data')
}

Invalidación de Caché

cacheTag() - Etiquetar Contenido en Caché

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() - Invalidación Inmediata

Úsalo cuando necesites que la caché se refresque dentro de la misma solicitud:

'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}`)  // Inmediato - la misma solicitud ve datos frescos
}

revalidateTag() - Revalidación en Segundo Plano

Úsalo para el comportamiento de obsoleto-mientras-revalida:

'use server'

import { revalidateTag } from 'next/cache'

export async function createPost(data: FormData) {
  await db.posts.create({ data })
  revalidateTag('posts')  // Segundo plano - la próxima solicitud ve datos frescos
}

Restricción de Datos en Tiempo de Ejecución

No se puede acceder a cookies(), headers() o searchParams dentro de use cache.

Solución: Pasar como Argumentos

// Incorrecto - API de tiempo de ejecución dentro de use cache
async function CachedProfile() {
  'use cache'
  const session = (await cookies()).get('session')?.value  // ¡Error!
  return <div>{session}</div>
}

// Correcto - extraer fuera, pasar como argumento
async function ProfilePage() {
  const session = (await cookies()).get('session')?.value
  return <CachedProfile sessionId={session} />
}

async function CachedProfile({ sessionId }: { sessionId: string }) {
  'use cache'
  // sessionId se convierte automáticamente en parte de la clave de caché
  const data = await fetchUserData(sessionId)
  return <div>{data.name}</div>
}

Excepción: use cache: private

Para requisitos de cumplimiento cuando no se puede refactorizar:

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

Generación de Claves de Caché

Las claves de caché se generan automáticamente basándose en:

  • ID de compilación - invalida todas las cachés al desplegar
  • ID de función - hash de la ubicación de la función
  • Argumentos serializables - las props se convierten en parte de la clave
  • Variables de cierre - se incluyen valores del ámbito externo
async function Component({ userId }: { userId: string }) {
  const getData = async (filter: string) => {
    'use cache'
    // Clave de caché = userId (cierre) + filter (argumento)
    return fetch(`/api/users/${userId}?filter=${filter}`)
  }
  return getData('active')
}

Ejemplo Completo

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

export default function DashboardPage() {
  return (
    <>
      {/* Esqueleto estático - instantáneo desde CDN */}
      <header><h1>Dashboard</h1></header>
      <nav>...</nav>

      {/* En caché - rápido, se revalida cada hora */}
      <Stats />

      {/* Dinámico - se transmite con datos frescos */}
      <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} />
}

Migración desde Versiones Anteriores

Configuración AntiguaReemplazo
experimental.pprcacheComponents: true
dynamic = 'force-dynamic'Eliminar (comportamiento por defecto)
dynamic = 'force-static''use cache' + cacheLife('max')
revalidate = NcacheLife({ revalidate: N })
unstable_cache()Directiva 'use cache'

Limitaciones

  • Edge runtime no soportado - requiere Node.js
  • Exportación estática no soportada - necesita servidor
  • Valores no deterministas (Math.random(), Date.now()) se ejecutan una vez en tiempo de compilación dentro de use cache

Para aleatoriedad en tiempo de solicitud fuera de la caché:

import { connection } from 'next/server'

async function DynamicContent() {
  await connection()  // Diferir al momento de la solicitud
  const id = crypto.randomUUID()  // Diferente por solicitud
  return <div>{id}</div>
}

Fuentes:

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 relacionados