C.W.K.
Stream
Lesson 09 of 09 · published

'use cache' Directive

~24 min · use cache, cacheLife, cacheTag

Level 0Curious
0 XP0/68 lessons0/11 achievements
0/120 XP to next level120 XP to go0% complete

Component level 에서 caching

Next.js 16 가 'use cache' 를 component 와 function 통째 작동하는 primitive 로 introduce, fetch() 만 아님. 실험적 unstable_cache 를 더 깔끔한 directive-based API 로 대체.

3 가지 building block

API용도
'use cache'Component 또는 function 을 cacheable 로 mark
cacheLife(profile)Cache duration 설정 (built-in profile 또는 custom)
cacheTag(...tags)On-demand invalidation 위해 cached output 에 tag

Built-in cacheLife profile

Profile name 사용하면 framework 가 합리적 default 골라: 'seconds', 'minutes', 'hours', 'days', 'weeks', 'max'. Custom profile 이 stale / revalidate / expire 독립적으로 설정 가능.

PPR 와 어떻게 compose

'use cache' 가 Partial Prerendering 와 integrate: cached component 가 build time 에 render 되고 static shell 일부 됨, 같은 route 에서 uncached 부분은 dynamic 유지.

Code

Component 통째 cache·tsx
'use cache';
import { cacheLife } from 'next/cache';

export default async function ProductList() {
  cacheLife('hours');
  const products = await db.product.findMany();
  return (
    <ul>
      {products.map(p => <li key={p.id}>{p.name} — ${p.price}</li>)}
    </ul>
  );
}
Invalidation 위한 tag 와 함께 function cache·ts
'use cache';
import { cacheTag } from 'next/cache';

export async function getProduct(id: string) {
  cacheTag('products', `product-${id}`);
  return db.product.findUnique({ where: { id } });
}

// Server Action 안:
import { updateTag } from 'next/cache';

export async function updateProduct(id: string, data: FormData) {
  'use server';
  await db.product.update({ where: { id }, data: { /* … */ } });
  updateTag(`product-${id}`); // 이 product 의 cache 만 invalidate
}

External links

Exercise

느린 DB query render 하는 component 에 'use cache' 추가. cacheLife('hours') 박고 다음 mutation 이 invalidation 위해 tag 할 때까지 component 가 request 너머로 reuse 되는지 확인.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.