Communitygithub.com

Componentes de Cache (Next.js 16+)

Componentes de Cache habilitam o Partial Prerendering (PPR) no Next.js 16+, permitindo misturar conteúdo estático, em cache e dinâmico em uma única rota.

O que é Componentes de Cache (Next.js 16+)?

Esta skill detalha o novo sistema de Componentes de Cache introduzido no Next.js 16+, substituindo o antigo flag `experimental.ppr`. Ela explica como ativar o recurso através da configuração `cacheComponents: true` e descreve os três tipos de conteúdo resultantes: estático (pré-renderizado automaticamente), cached (usando a diretiva `'use cache'`) e dinâmico (envolvido em Suspense para streaming). A documentação cobre profundamente a diretiva `'use cache'` em nível de arquivo, componente e função, os perfis de cache integrados e customizáveis via `cacheLife()`, e a invalidação de cache com `cacheTag()`, `updateTag()` e `revalidateTag()`. Uma restrição importante é que APIs de runtime como `cookies()`, `headers()` ou `searchParams` não podem ser acessadas diretamente dentro de `use cache`, exigindo que sejam passadas como argumentos. A skill é útil para desenvolvedores que desejam otimizar o desempenho de páginas Next.js combinando conteúdo pré-renderizado com dados atualizados, suporta Node.js (não Edge runtime) e é aplicável ao App Router do Next.js.

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

Perguntar na sua IA favorita

Abre um novo chat com esta habilidade de agente já pré-carregada.

Documentação

O que Componentes de Cache (Next.js 16+) faz?

Os Componentes de Cache habilitam o Partial Prerendering (PPR) – misture conteúdo estático, cached e dinâmico em uma única rota.

Ativar Componentes de Cache

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

const nextConfig: NextConfig = {
  cacheComponents: true,
}

export default nextConfig

Isso substitui o antigo flag experimental.ppr.


Três Tipos de Conteúdo

Com os Componentes de Cache ativados, o conteúdo se enquadra em três categorias:

1. Estático (Pré-renderizado Automaticamente)

Código síncrono, importações, computações puras – pré-renderizado em tempo de build:

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

2. Em Cache (use cache)

Dados assíncronos que não precisam de buscas novas a cada requisição:

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

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

3. Dinâmico (Suspense)

Dados de runtime que precisam estar frescos – envolva em Suspense:

import { Suspense } from 'react'

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

      <Suspense fallback={<p>Carregando...</p>}>
        <UserPreferences />  {/* Dinâmico - entra em streaming */}
      </Suspense>
    </>
  )
}

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

Diretiva use cache

Nível de Arquivo

'use cache'

export default async function Page() {
  // Página inteira é armazenada em cache
  const data = await fetchData()
  return <div>{data}</div>
}

Nível de Componente

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

Nível de Função

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

Perfis de Cache

Perfis Integrados

'use cache'                    // Padrão: 5 min stale, 15 min revalidação
'use cache: remote'           // Cache fornecido pela plataforma (Redis, KV)
'use cache: private'          // Para conformidade, permite APIs de runtime

cacheLife() - Vida Útil Personalizada

import { cacheLife } from 'next/cache'

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

Perfis integrados: 'default', 'minutes', 'hours', 'days', 'weeks', 'max'

Configuração Inline

async function getData() {
  'use cache'
  cacheLife({
    stale: 3600,      // 1 hora - serve stale enquanto revalida
    revalidate: 7200, // 2 horas - intervalo de revalidação em segundo plano
    expire: 86400,    // 1 dia - expiração forçada
  })
  return fetch('/api/data')
}

Invalidação de Cache

cacheTag() - Marcar Conteúdo em 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() - Invalidação Imediata

Use quando precisar que o cache seja atualizado dentro da mesma requisição:

'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}`)  // Imediato - mesma requisição vê dados frescos
}

revalidateTag() - Revalidação em Segundo Plano

Use para comportamento stale-while-revalidate:

'use server'

import { revalidateTag } from 'next/cache'

export async function createPost(data: FormData) {
  await db.posts.create({ data })
  revalidateTag('posts')  // Segundo plano - próxima requisição vê dados frescos
}

Restrição de Dados de Runtime

Não é possível acessar cookies(), headers() ou searchParams dentro de use cache.

Solução: Passe como Argumentos

// Errado - API de runtime dentro de use cache
async function CachedProfile() {
  'use cache'
  const session = (await cookies()).get('session')?.value  // Erro!
  return <div>{session}</div>
}

// Correto - extraia fora, passe 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 torna parte da chave de cache automaticamente
  const data = await fetchUserData(sessionId)
  return <div>{data.name}</div>
}

Exceção: use cache: private

Para requisitos de conformidade quando não é possível refatorar:

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

Geração de Chave de Cache

As chaves de cache são automáticas e baseadas em:

  • Build ID - invalida todos os caches no deploy
  • Function ID - hash da localização da função
  • Argumentos serializáveis - props se tornam parte da chave
  • Variáveis de closure - valores do escopo externo incluídos
async function Component({ userId }: { userId: string }) {
  const getData = async (filter: string) => {
    'use cache'
    // Chave de cache = userId (closure) + filter (argumento)
    return fetch(`/api/users/${userId}?filter=${filter}`)
  }
  return getData('active')
}

Exemplo Completo

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

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

      {/* Em cache - rápido, revalida a cada hora */}
      <Stats />

      {/* Dinâmico - entra em streaming com dados 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} />
}

Migração de Versões Anteriores

Configuração AntigaSubstituição
experimental.pprcacheComponents: true
dynamic = 'force-dynamic'Remover (comportamento padrão)
dynamic = 'force-static''use cache' + cacheLife('max')
revalidate = NcacheLife({ revalidate: N })
unstable_cache()Diretiva 'use cache'

Limitações

  • Runtime Edge não suportado - requer Node.js
  • Exportação estática não suportada - precisa de servidor
  • Valores não determinísticos (Math.random(), Date.now()) executam uma vez em tempo de build dentro de use cache

Para aleatoriedade em tempo de requisição fora do cache:

import { connection } from 'next/server'

async function DynamicContent() {
  await connection()  // Adiar para o tempo de requisição
  const id = crypto.randomUUID()  // Diferente por requisição
  return <div>{id}</div>
}

Fontes:

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

Habilidades Relacionadas