Communitygithub.com

ComeOnOliver/skillshub

Next.js 16 캐시 컴포넌트 - PPR, use cache 지시어, cacheLife, cacheTag, updateTag

skillshub란 무엇인가요?

이 스킬은 Next.js 16+에서 도입된 캐시 컴포넌트(Cache Components) 시스템을 상세히 설명합니다. Partial Prerendering(PPR)을 활성화하여 단일 라우트 내에서 정적 콘텐츠, 캐시된 콘텐츠, 동적 콘텐츠를 자연스럽게 혼합할 수 있습니다. `next.config.ts`에서 `cacheComponents: true` 플래그를 설정하여 활성화하며, 기존 `experimental.ppr`을 대체합니다. 스킬은 `use cache` 지시어를 파일, 컴포넌트, 함수 수준에서 사용하는 방법, `cacheLife`로 캐시 수명 주기를 제어하는 방법, `cacheTag`와 `updateTag`를 통한 캐시 무효화 전략을 다룹니다. 또한 `cookies()`, `headers()`, `searchParams`와 같은 런타임 데이터 접근 제약 조건과 해결 방법을 제공하며, 엣지 런타임 및 정적 내보내기 미지원 등의 제한 사항도 포함하고 있습니다. Cursor, Codex, Claude Code와 같은 AI 에이전트 플랫폼에서 이 지침을 활용하면 최신 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 플래그를 대체합니다.


세 가지 콘텐츠 유형

캐시 컴포넌트가 활성화되면 콘텐츠는 세 가지 범주로 나뉩니다:

1. 정적 (자동 사전 렌더링)

동기 코드, 임포트, 순수 계산 - 빌드 타임에 사전 렌더링:

export default function Page() {
  return (
    <header>
      <h1>Our Blog</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분 만료, 15분 재검증
'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시간 - 재검증 중 만료된 데이터 제공
    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>

      {/* 캐시됨 - 빠르며, 매시간 재검증 */}
      <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' 지시어

제한 사항

  • 엣지 런타임 미지원 - Node.js 필요
  • 정적 내보내기 미지원 - 서버 필요
  • 비결정적 값 (Math.random(), Date.now())은 use cache 내부에서 빌드 타임에 한 번만 실행됨

캐시 외부에서 요청 시간 무작위성 필요 시:

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

관련 스킬