본문으로 건너뛰기

'use cache'

Next.js 목차 미리 그리기와 캐시 레슨 23 / 47

목차

'use cache'는 Next.js의 지시어로, 함수 몸 맨 앞에 두면 그 함수가 돌려준 값을 기억해 둡니다. 이 레슨은 lib/recipes.ts의 getRecipes에 'use cache' · cacheLife('hours') · cacheTag('recipes')를 달고, 다음 요청에 함수가 다시 도는지를 서버 터미널과 빌드 출력으로 봅니다.

빌드가 미리 그린 것에서 /stats는 ◐였습니다. 요청이 올 때마다 getRecipes가 같은 파일을 다시 읽어 모두 4개를 채웠습니다. 파일이 그대로인 동안에도 요청마다 읽습니다. 읽은 결과를 기억해 두면 어떻게 될까요?

1함수 머리에 'use cache'

개발 서버를 켜 둔 채 따라 합니다. lib/recipes.ts 맨 위에 next/cache의 cacheLife · cacheTag를 가져오는 import를 더하고, getRecipes 몸의 맨 앞에 'use cache';를 둡니다. 함수가 돌 때를 보려고 console.log 한 줄도 넣습니다.

lib/recipes.ts
…
// 1. 함수 머리에 'use cache'
export const getRecipes =
  async () => {
    'use cache';
    // 2. cacheLife로 얼마나
    cacheLife('hours');
    // 3. cacheTag로 이름 붙이기
    cacheTag('recipes');
    console.log(
      '레시피 파일 읽음',
    );
    const text = await readFile(
…
  • 'use cache' — 이 함수가 돌려준 값을 기억해 둡니다. 함수 몸의 맨 앞 줄이어야 합니다. 파일 맨 위에 두면 그 파일이 내보내는 함수가 모두 기억합니다. 어느 꼴이든 기억하는 함수는 async여야 합니다(Next.js 문서 use cache).
  • cacheLife('hours') — 한 시간쯤 기억합니다. 정확한 수는 얼마나 기억하나에서 봅니다.
  • cacheTag('recipes') — 기억한 값에 이름 recipes를 붙입니다. 기억을 지울 때 부르는 이름으로, 단원 6에서 씁니다.

레시피 보관함을 연 탭은 모두 닫고 저장합니다. 열어 둔 탭이 있으면 저장하자마자 개발 서버가 그 쪽을 스스로 다시 받아, getRecipes가 그때 먼저 돕니다. 그다음 새 탭 주소 칸에 /recipes를 쳐서 목록을 엽니다. 그 탭에서 한 번 더 엽니다.

lib/recipes.ts 전체 · 서버 터미널 · 브라우저 콘솔

아래는 고친 lib/recipes.ts 전체, 목록을 처음 연 뒤와 다시 연 뒤의 서버 터미널, 다시 연 뒤의 브라우저 콘솔입니다. 시간은 다를 수 있습니다.

lib/recipes.ts
import {
  readFile,
} from 'node:fs/promises';
import {
  cacheLife,
  cacheTag,
} from 'next/cache';

export interface Recipe {
  id: string;
  title: string;
  category: string;
  minutes: number;
  ingredients: string[];
  favorite: boolean;
}

export const categories = [
  '한식',
  '양식',
  '일식',
  '중식',
  '디저트',
];

function isRecipe(
  v: unknown,
): v is Recipe {
  return (
    typeof v === 'object' &&
    v !== null &&
    'id' in v &&
    'title' in v &&
    'category' in v &&
    'minutes' in v &&
    'ingredients' in v &&
    'favorite' in v &&
    typeof v.id === 'string' &&
    typeof v.title ===
      'string' &&
    typeof v.category ===
      'string' &&
    typeof v.minutes ===
      'number' &&
    Array.isArray(
      v.ingredients,
    ) &&
    typeof v.favorite ===
      'boolean'
  );
}

// 1. 함수 머리에 'use cache'
export const getRecipes =
  async () => {
    'use cache';
    // 2. cacheLife로 얼마나
    cacheLife('hours');
    // 3. cacheTag로 이름 붙이기
    cacheTag('recipes');
    console.log(
      '레시피 파일 읽음',
    );
    const text = await readFile(
      'data/recipes.json',
      'utf8',
    );
    const data: unknown =
      JSON.parse(text);
    return Array.isArray(data)
      ? data.filter(isRecipe)
      : [];
  };

export const getRecipe =
  async (id: string) => {
    const list =
      await getRecipes();
    return list.find(
      (r) => r.id === id,
    );
  };
실행 결과
> recipe-box-next@0.1.0 dev
> next dev

▲ Next.js 16.4.6 (Turbopack)
- Local:         http://localhost:3000
- Network:       http://127.131.113.34:3000
✓ Ready in 276ms
✓ Running next.config.ts took 1128ms
- Cache Components enabled
- Partial Prefetching enabled

레시피 파일 읽음
 Cache  레시피 파일 읽음
 GET /recipes 200 in 266ms (next.js: 85ms, application-code: 181ms)
 Cache  레시피 파일 읽음
 Cache  레시피 파일 읽음
> recipe-box-next@0.1.0 dev
> next dev

▲ Next.js 16.4.6 (Turbopack)
- Local:         http://localhost:3000
- Network:       http://127.131.113.34:3000
✓ Ready in 276ms
✓ Running next.config.ts took 1128ms
- Cache Components enabled
- Partial Prefetching enabled

레시피 파일 읽음
 Cache  레시피 파일 읽음
 GET /recipes 200 in 266ms (next.js: 85ms, application-code: 181ms)
 Cache  레시피 파일 읽음
 Cache  레시피 파일 읽음
 Cache  레시피 파일 읽음
 GET /recipes 200 in 162ms (next.js: 2ms, application-code: 160ms)
[Cache] 레시피 파일 읽음

처음 열었을 때 새로 찍힌 줄에는 꼬리표 없는 레시피 파일 읽음이 한 줄 있습니다. getRecipes가 돌아 파일을 읽고, 그 결과를 기억해 둔 것입니다. 앞에 Cache가 붙은 같은 글도 함께 찍혔습니다. 다시 열었을 때 새로 찍힌 줄에는 꼬리표 없는 줄이 없고, Cache가 붙은 줄만 있습니다. 브라우저 콘솔에도 [Cache] 꼬리표를 단 같은 줄이 보입니다.

2Cache 꼬리표가 붙은 줄

꼬리표가 붙은 줄은 함수가 다시 돌며 찍은 줄이 아닙니다. 개발 판은 기억해 둔 결과를 줄 때, 그 함수가 처음 돌며 찍었던 로그를 꼬리표 Cache를 붙여 다시 보여 줍니다(Next.js 문서 use cache 'Console log replays' — 'console logs from cached functions appear with a Cache prefix'). 두 번째 요청에서 getRecipes는 돌지 않았고, 파일도 다시 읽지 않았습니다. 꼬리표 줄은 요청 하나에 여러 줄 찍히기도 해서, 함수가 돌았는지는 꼬리표 없는 줄로 가립니다.

Next.js 규칙 7. 'use cache'는 결과를 인자로 기억합니다. 같은 인자로 부르면 함수를 다시 돌리지 않고 기억한 결과를 줍니다. 얼마나 기억할지는 cacheLife, 지울 때 부를 이름은 cacheTag로 정합니다.

getRecipes는 인자가 없으니, 목록 쪽에서 부르든 통계 쪽에서 부르든 같은 부름입니다. 인자가 있는 함수는 인자가 열쇠다에서 봅니다.

3빌드 출력의 Revalidate · Expire 칸

개발 서버를 Ctrl+C로 끄고 npm run build를 친 뒤, npm run start로 띄워 /stats의 받은 HTML과 응답 머리를 봅니다.

lib/recipes.ts 전체 · 빌드 출력 · 받은 HTML · 응답 머리

아래는 1절 그대로의 lib/recipes.ts, 빌드 출력, 배포 판 /stats의 받은 HTML(다듬음)과 응답 머리입니다.

lib/recipes.ts
import {
  readFile,
} from 'node:fs/promises';
import {
  cacheLife,
  cacheTag,
} from 'next/cache';

export interface Recipe {
  id: string;
  title: string;
  category: string;
  minutes: number;
  ingredients: string[];
  favorite: boolean;
}

export const categories = [
  '한식',
  '양식',
  '일식',
  '중식',
  '디저트',
];

function isRecipe(
  v: unknown,
): v is Recipe {
  return (
    typeof v === 'object' &&
    v !== null &&
    'id' in v &&
    'title' in v &&
    'category' in v &&
    'minutes' in v &&
    'ingredients' in v &&
    'favorite' in v &&
    typeof v.id === 'string' &&
    typeof v.title ===
      'string' &&
    typeof v.category ===
      'string' &&
    typeof v.minutes ===
      'number' &&
    Array.isArray(
      v.ingredients,
    ) &&
    typeof v.favorite ===
      'boolean'
  );
}

// 1. 함수 머리에 'use cache'
export const getRecipes =
  async () => {
    'use cache';
    // 2. cacheLife로 얼마나
    cacheLife('hours');
    // 3. cacheTag로 이름 붙이기
    cacheTag('recipes');
    console.log(
      '레시피 파일 읽음',
    );
    const text = await readFile(
      'data/recipes.json',
      'utf8',
    );
    const data: unknown =
      JSON.parse(text);
    return Array.isArray(data)
      ? data.filter(isRecipe)
      : [];
  };

export const getRecipe =
  async (id: string) => {
    const list =
      await getRecipes();
    return list.find(
      (r) => r.id === id,
    );
  };
실행 결과
  Creating an optimized production build ...
✓ Compiled successfully in 2.6s
  Running TypeScript ...
  Finished TypeScript in 1724ms ...
  Collecting page data using 8 workers ...
레시피 파일 읽음
✓ Collecting page data using 8 workers in 684ms
  Generating static pages using 8 workers (0/11) ...
레시피 파일 읽음
  Generating static pages using 8 workers (2/11)
  Generating static pages using 8 workers (5/11)
  Generating static pages using 8 workers (8/11)
✓ Generating static pages using 8 workers (11/11) in 725ms
  Finalizing page optimization ...
✓ Finalizing page optimization in 21ms

Route (app)            Revalidate  Expire
┌ ◐ /                          1h      1d
├ ○ /_not-found
├ ◐ /recipes
├   /recipes/[id]
│ ├ ◐ /recipes/[id]
│ ├ ○ /recipes/r1              1h      1d
│ ├ ○ /recipes/r2              1h      1d
│ └ ◐ [+2 more paths]
└ ○ /stats                     1h      1d


○  (Static)             prerendered as static content
◐  (Partial Prerender)  prerendered as static HTML with dynamic server-streamed content
HTML
<nav><a href="/recipes">목록</a>·<a href="/stats">▸ 통계</a></nav><h1>통계</h1><p>모두 4개</p><footer>바닥글</footer>
결과 화면
HTTP/1.1 200 OK
x-nextjs-cache: HIT
x-nextjs-prerender: 1
x-nextjs-prerender: 1
Cache-Control: s-maxage=3600, stale-while-revalidate=82800
Content-Type: text/html; charset=utf-8

빌드 출력의 Collecting page data 아래와 Generating static pages 아래에 레시피 파일 읽음이 한 줄씩 찍혔습니다. 빌드가 두 단계에서 getRecipes를 불렀습니다. 경로 표에는 Revalidate · Expire 칸이 생겼고, /stats 줄은 ○에 1h · 1d입니다. 두 칸은 cacheLife('hours')가 정한 수로, 뜻은 다음 레슨에서 읽습니다. /stats의 받은 HTML에는 세는 중도 구멍 표시도 없고 모두 4개가 바로 듭니다. 빌드가 getRecipes의 결과를 기다려 껍데기에 넣었습니다. 응답 머리의 x-nextjs-cache: HIT는 빌드가 미리 그린 것의 해 보기처럼, 기억해 둔 쪽을 통째로 준 표시입니다.

/recipes는 ◐ 그대로입니다. RecipeList가 주소의 검색어(searchParams)를 먼저 기다리니, 목록은 요청 때 그립니다. 다만 그때 부르는 getRecipes는 서버를 띄운 뒤 처음 한 번 읽고, 그다음부터는 기억한 결과를 줍니다(예제).

해 보기 — 데이터 파일만 고치면

개발 판에서 데이터 파일만 고치면 목록은 어떻게 될까요? 배포 판을 Ctrl+C로 끄고 npm run dev로 개발 서버를 띄운 뒤 차례대로 합니다.

  1. 주소 칸에 /recipes를 쳐서 목록을 한 번 엽니다.
  2. data/recipes.json에 레시피 하나를 더하고 저장합니다. 끝 레시피의 닫는 } 뒤에 쉼표를 찍고 아래를 붙입니다.
  3. 주소 칸에 /recipes를 쳐서 목록을 다시 엽니다.
data/recipes.json
…
  {
    "id": "r5",
    "title": "된장찌개",
    "category": "한식",
    "minutes": 20,
    "ingredients": [
      "된장",
      "두부"
    ],
    "favorite": false
  }
]

3에서 다시 연 목록은 어떨까요? 고른 뒤 펼쳐 보세요. 맞혀 보기는 점수에 들지 않습니다.

  • ① 된장찌개까지 다섯이 보인다 — 개발 서버는 파일이 바뀌면 다시 읽으니까
  • ② 넷 그대로다 — 기억해 둔 결과를 주니까
  • ③ 목록 자리가 목록을 읽는 중에서 멈춘다
결과 보기

②입니다. 데이터 파일은 코드가 아니라, 고쳐도 기억은 남습니다. 개발 서버가 기억해 둔 것을 지우는 것은 쪽이 쓰는 코드 파일을 고쳐 저장할 때입니다(Next.js 문서 use cache 'Cache keys' — 'HMR refresh hash (development only)'). 이어서 차례대로 해 봅니다.

  1. lib/recipes.ts의 로그 글을 '레시피 파일 새로 읽음'으로 고쳐 저장하고, 목록을 다시 엽니다.
  2. data/recipes.json을 레시피 넷으로 되돌린 뒤, 로그 글을 '레시피 파일 읽음'으로 되돌려 저장하고, 목록을 다시 엽니다.

아래는 차례대로 1절 그대로의 lib/recipes.ts, 레시피를 더한 data/recipes.json 전체, 3에서 다시 연 목록의 화면에 보이는 <body> 안 HTML, 서버 터미널, 4에서 로그 글을 고친 lib/recipes.ts, 그 뒤 연 목록의 화면, 5에서 되돌린 data/recipes.json · lib/recipes.ts, 그 뒤 연 목록의 화면입니다.

lib/recipes.ts
import {
  readFile,
} from 'node:fs/promises';
import {
  cacheLife,
  cacheTag,
} from 'next/cache';

export interface Recipe {
  id: string;
  title: string;
  category: string;
  minutes: number;
  ingredients: string[];
  favorite: boolean;
}

export const categories = [
  '한식',
  '양식',
  '일식',
  '중식',
  '디저트',
];

function isRecipe(
  v: unknown,
): v is Recipe {
  return (
    typeof v === 'object' &&
    v !== null &&
    'id' in v &&
    'title' in v &&
    'category' in v &&
    'minutes' in v &&
    'ingredients' in v &&
    'favorite' in v &&
    typeof v.id === 'string' &&
    typeof v.title ===
      'string' &&
    typeof v.category ===
      'string' &&
    typeof v.minutes ===
      'number' &&
    Array.isArray(
      v.ingredients,
    ) &&
    typeof v.favorite ===
      'boolean'
  );
}

// 1. 함수 머리에 'use cache'
export const getRecipes =
  async () => {
    'use cache';
    // 2. cacheLife로 얼마나
    cacheLife('hours');
    // 3. cacheTag로 이름 붙이기
    cacheTag('recipes');
    console.log(
      '레시피 파일 읽음',
    );
    const text = await readFile(
      'data/recipes.json',
      'utf8',
    );
    const data: unknown =
      JSON.parse(text);
    return Array.isArray(data)
      ? data.filter(isRecipe)
      : [];
  };

export const getRecipe =
  async (id: string) => {
    const list =
      await getRecipes();
    return list.find(
      (r) => r.id === id,
    );
  };
data/recipes.json
[
  {
    "id": "r1",
    "title": "김치볶음밥",
    "category": "한식",
    "minutes": 15,
    "ingredients": [
      "밥",
      "김치",
      "달걀"
    ],
    "favorite": true
  },
  {
    "id": "r2",
    "title": "토마토 파스타",
    "category": "양식",
    "minutes": 25,
    "ingredients": [
      "파스타",
      "토마토"
    ],
    "favorite": false
  },
  {
    "id": "r3",
    "title": "계란말이",
    "category": "한식",
    "minutes": 10,
    "ingredients": [
      "달걀",
      "파"
    ],
    "favorite": false
  },
  {
    "id": "r4",
    "title": "바나나 팬케이크",
    "category": "디저트",
    "minutes": 20,
    "ingredients": [
      "바나나",
      "밀가루",
      "우유"
    ],
    "favorite": true
  },
  {
    "id": "r5",
    "title": "된장찌개",
    "category": "한식",
    "minutes": 20,
    "ingredients": [
      "된장",
      "두부"
    ],
    "favorite": false
  }
]
<nav><a href="/recipes">▸ 목록</a>·<a href="/stats">통계</a></nav><section><h1>레시피</h1><form action="/recipes"><input name="q"><button>찾기</button></form><ul><li><a href="/recipes/r1">김치볶음밥</a><button>★</button></li><li><a href="/recipes/r2">토마토 파스타</a><button>☆</button></li><li><a href="/recipes/r3">계란말이</a><button>☆</button></li><li><a href="/recipes/r4">바나나 팬케이크</a><button>★</button></li></ul></section><footer>바닥글</footer>
결과 화면
> recipe-box-next@0.1.0 dev
> next dev

▲ Next.js 16.4.6 (Turbopack)
- Local:         http://localhost:3000
- Network:       http://127.131.113.34:3000
✓ Ready in 297ms
✓ Running next.config.ts took 1215ms
- Cache Components enabled
- Partial Prefetching enabled

레시피 파일 읽음
 Cache  레시피 파일 읽음
 GET /recipes 200 in 241ms (next.js: 87ms, application-code: 155ms)
 Cache  레시피 파일 읽음
 Cache  레시피 파일 읽음
 Cache  레시피 파일 읽음
 GET /recipes 200 in 32ms (next.js: 0.8ms, application-code: 31ms)
lib/recipes.ts
import {
  readFile,
} from 'node:fs/promises';
import {
  cacheLife,
  cacheTag,
} from 'next/cache';

export interface Recipe {
  id: string;
  title: string;
  category: string;
  minutes: number;
  ingredients: string[];
  favorite: boolean;
}

export const categories = [
  '한식',
  '양식',
  '일식',
  '중식',
  '디저트',
];

function isRecipe(
  v: unknown,
): v is Recipe {
  return (
    typeof v === 'object' &&
    v !== null &&
    'id' in v &&
    'title' in v &&
    'category' in v &&
    'minutes' in v &&
    'ingredients' in v &&
    'favorite' in v &&
    typeof v.id === 'string' &&
    typeof v.title ===
      'string' &&
    typeof v.category ===
      'string' &&
    typeof v.minutes ===
      'number' &&
    Array.isArray(
      v.ingredients,
    ) &&
    typeof v.favorite ===
      'boolean'
  );
}

// 1. 함수 머리에 'use cache'
export const getRecipes =
  async () => {
    'use cache';
    // 2. cacheLife로 얼마나
    cacheLife('hours');
    // 3. cacheTag로 이름 붙이기
    cacheTag('recipes');
    console.log(
      '레시피 파일 새로 읽음',
    );
    const text = await readFile(
      'data/recipes.json',
      'utf8',
    );
    const data: unknown =
      JSON.parse(text);
    return Array.isArray(data)
      ? data.filter(isRecipe)
      : [];
  };

export const getRecipe =
  async (id: string) => {
    const list =
      await getRecipes();
    return list.find(
      (r) => r.id === id,
    );
  };
<nav><a href="/recipes">▸ 목록</a>·<a href="/stats">통계</a></nav><section><h1>레시피</h1><form action="/recipes"><input name="q"><button>찾기</button></form><ul><li><a href="/recipes/r1">김치볶음밥</a><button>★</button></li><li><a href="/recipes/r2">토마토 파스타</a><button>☆</button></li><li><a href="/recipes/r3">계란말이</a><button>☆</button></li><li><a href="/recipes/r4">바나나 팬케이크</a><button>★</button></li><li><a href="/recipes/r5">된장찌개</a><button>☆</button></li></ul></section><footer>바닥글</footer>
결과 화면
data/recipes.json
[
  {
    "id": "r1",
    "title": "김치볶음밥",
    "category": "한식",
    "minutes": 15,
    "ingredients": [
      "밥",
      "김치",
      "달걀"
    ],
    "favorite": true
  },
  {
    "id": "r2",
    "title": "토마토 파스타",
    "category": "양식",
    "minutes": 25,
    "ingredients": [
      "파스타",
      "토마토"
    ],
    "favorite": false
  },
  {
    "id": "r3",
    "title": "계란말이",
    "category": "한식",
    "minutes": 10,
    "ingredients": [
      "달걀",
      "파"
    ],
    "favorite": false
  },
  {
    "id": "r4",
    "title": "바나나 팬케이크",
    "category": "디저트",
    "minutes": 20,
    "ingredients": [
      "바나나",
      "밀가루",
      "우유"
    ],
    "favorite": true
  }
]
lib/recipes.ts
import {
  readFile,
} from 'node:fs/promises';
import {
  cacheLife,
  cacheTag,
} from 'next/cache';

export interface Recipe {
  id: string;
  title: string;
  category: string;
  minutes: number;
  ingredients: string[];
  favorite: boolean;
}

export const categories = [
  '한식',
  '양식',
  '일식',
  '중식',
  '디저트',
];

function isRecipe(
  v: unknown,
): v is Recipe {
  return (
    typeof v === 'object' &&
    v !== null &&
    'id' in v &&
    'title' in v &&
    'category' in v &&
    'minutes' in v &&
    'ingredients' in v &&
    'favorite' in v &&
    typeof v.id === 'string' &&
    typeof v.title ===
      'string' &&
    typeof v.category ===
      'string' &&
    typeof v.minutes ===
      'number' &&
    Array.isArray(
      v.ingredients,
    ) &&
    typeof v.favorite ===
      'boolean'
  );
}

// 1. 함수 머리에 'use cache'
export const getRecipes =
  async () => {
    'use cache';
    // 2. cacheLife로 얼마나
    cacheLife('hours');
    // 3. cacheTag로 이름 붙이기
    cacheTag('recipes');
    console.log(
      '레시피 파일 읽음',
    );
    const text = await readFile(
      'data/recipes.json',
      'utf8',
    );
    const data: unknown =
      JSON.parse(text);
    return Array.isArray(data)
      ? data.filter(isRecipe)
      : [];
  };

export const getRecipe =
  async (id: string) => {
    const list =
      await getRecipes();
    return list.find(
      (r) => r.id === id,
    );
  };
<nav><a href="/recipes">▸ 목록</a>·<a href="/stats">통계</a></nav><section><h1>레시피</h1><form action="/recipes"><input name="q"><button>찾기</button></form><ul><li><a href="/recipes/r1">김치볶음밥</a><button>★</button></li><li><a href="/recipes/r2">토마토 파스타</a><button>☆</button></li><li><a href="/recipes/r3">계란말이</a><button>☆</button></li><li><a href="/recipes/r4">바나나 팬케이크</a><button>★</button></li></ul></section><footer>바닥글</footer>
결과 화면

3에서 다시 연 뒤 새로 찍힌 줄에는 꼬리표 없는 레시피 파일 읽음이 없고, Cache가 붙은 줄만 있습니다. getRecipes는 다시 돌지 않고 1에서 기억한 목록을 주었습니다. 4에서 코드 파일을 고쳐 저장한 뒤 연 목록은 된장찌개까지 다섯이고, 5에서 되돌린 뒤에는 다시 넷입니다.

4에서는 목록 탭이 열려 있어, 저장하자마자 개발 서버가 그 쪽을 스스로 다시 받고 기억이 곧바로 새 목록으로 찹니다. 그래서 개발 판에서 기억을 볼 때는 '코드를 고쳐 저장 → 목록을 한 번 연다 → 데이터를 바꾼다 → 다시 연다' 차례를 지킵니다.

다 봤으면 data/recipes.json은 레시피 넷, 로그 글은 '레시피 파일 읽음'이어야 합니다(결과 보기의 5).

예제

같은 일을 배포 판으로 합니다. 개발 서버를 끄고 npm run build → npm run start로 띄운 뒤 /recipes를 한 번 엽니다. 그다음 몇 분 안에 이어서, data/recipes.json에 해 보기의 된장찌개를 더하고 다시 빌드하지 않고 /recipes를 다시 엽니다. 목록은 어떨까요? 고른 뒤 펼쳐 보세요. 맞혀 보기는 점수에 들지 않습니다.

  • ① 넷 그대로다
  • ② 된장찌개까지 다섯이다 — 목록 쪽은 ◐라 요청 때 그리니까
  • ③ 빌드 뒤 파일이 바뀌어 오류 쪽이 뜬다
결과 보기

①입니다. 아래는 1절 그대로의 lib/recipes.ts, 배포 판을 띄워 목록을 처음 연 뒤의 서버 터미널, 레시피를 더한 data/recipes.json, 다시 연 목록의 받은 HTML(다듬음)과 서버 터미널입니다.

lib/recipes.ts
import {
  readFile,
} from 'node:fs/promises';
import {
  cacheLife,
  cacheTag,
} from 'next/cache';

export interface Recipe {
  id: string;
  title: string;
  category: string;
  minutes: number;
  ingredients: string[];
  favorite: boolean;
}

export const categories = [
  '한식',
  '양식',
  '일식',
  '중식',
  '디저트',
];

function isRecipe(
  v: unknown,
): v is Recipe {
  return (
    typeof v === 'object' &&
    v !== null &&
    'id' in v &&
    'title' in v &&
    'category' in v &&
    'minutes' in v &&
    'ingredients' in v &&
    'favorite' in v &&
    typeof v.id === 'string' &&
    typeof v.title ===
      'string' &&
    typeof v.category ===
      'string' &&
    typeof v.minutes ===
      'number' &&
    Array.isArray(
      v.ingredients,
    ) &&
    typeof v.favorite ===
      'boolean'
  );
}

// 1. 함수 머리에 'use cache'
export const getRecipes =
  async () => {
    'use cache';
    // 2. cacheLife로 얼마나
    cacheLife('hours');
    // 3. cacheTag로 이름 붙이기
    cacheTag('recipes');
    console.log(
      '레시피 파일 읽음',
    );
    const text = await readFile(
      'data/recipes.json',
      'utf8',
    );
    const data: unknown =
      JSON.parse(text);
    return Array.isArray(data)
      ? data.filter(isRecipe)
      : [];
  };

export const getRecipe =
  async (id: string) => {
    const list =
      await getRecipes();
    return list.find(
      (r) => r.id === id,
    );
  };
실행 결과
> recipe-box-next@0.1.0 start
> next start

▲ Next.js 16.4.6
- Local:         http://localhost:3000
- Network:       http://127.131.113.34:3000
✓ Ready in 83ms
✓ Running next.config.ts took 18ms
레시피 파일 읽음
data/recipes.json
[
  {
    "id": "r1",
    "title": "김치볶음밥",
    "category": "한식",
    "minutes": 15,
    "ingredients": [
      "밥",
      "김치",
      "달걀"
    ],
    "favorite": true
  },
  {
    "id": "r2",
    "title": "토마토 파스타",
    "category": "양식",
    "minutes": 25,
    "ingredients": [
      "파스타",
      "토마토"
    ],
    "favorite": false
  },
  {
    "id": "r3",
    "title": "계란말이",
    "category": "한식",
    "minutes": 10,
    "ingredients": [
      "달걀",
      "파"
    ],
    "favorite": false
  },
  {
    "id": "r4",
    "title": "바나나 팬케이크",
    "category": "디저트",
    "minutes": 20,
    "ingredients": [
      "바나나",
      "밀가루",
      "우유"
    ],
    "favorite": true
  },
  {
    "id": "r5",
    "title": "된장찌개",
    "category": "한식",
    "minutes": 20,
    "ingredients": [
      "된장",
      "두부"
    ],
    "favorite": false
  }
]
HTML
<nav><a href="/recipes">▸ 목록</a>·<a href="/stats">통계</a></nav><section><h1>레시피</h1><form action="/recipes"><input name="q"/><button>찾기</button></form><template id="B:0"></template><p>목록을 읽는 중</p></section><footer>바닥글</footer><div hidden id="S:0"><ul><li><a href="/recipes/r1">김치볶음밥</a><button>★</button></li><li><a href="/recipes/r2">토마토 파스타</a><button>☆</button></li><li><a href="/recipes/r3">계란말이</a><button>☆</button></li><li><a href="/recipes/r4">바나나 팬케이크</a><button>★</button></li></ul></div>
결과 화면
> recipe-box-next@0.1.0 start
> next start

▲ Next.js 16.4.6
- Local:         http://localhost:3000
- Network:       http://127.131.113.34:3000
✓ Ready in 83ms
✓ Running next.config.ts took 18ms
레시피 파일 읽음

배포 판 서버는 띄운 뒤 목록을 처음 열 때 레시피 파일 읽음을 한 번 찍고, 다시 열 때는 찍지 않습니다. 목록 쪽은 ◐라 요청 때 그리지만, 그리면서 부른 getRecipes가 기억한 결과를 주어 파일을 다시 읽지 않았습니다. 배포 판은 꼬리표 Cache 줄도 찍지 않습니다.

다 봤으면 배포 판을 끄고 data/recipes.json을 레시피 넷으로 되돌린 뒤 npm run dev로 개발 서버를 다시 띄웁니다.

자주 틀리는 곳

틀린 생각: 'use cache'를 붙여도 함수는 부를 때마다 돌고, 데이터 파일을 바꾸면 다음 요청에 바로 보인다.

맞는 규칙: 기억이 남아 있는 동안 같은 인자로 부르면 함수를 다시 돌리지 않고 기억한 결과를 줍니다. 얼마나 남는지는 다음 레슨의 cacheLife가 정합니다. 배포 판 목록은 데이터를 고친 뒤에도 넷 그대로였습니다(예제). 기억을 지워 새로 읽게 하는 길은 단원 6에서 봅니다.

틀린 생각: 개발 서버 터미널에 레시피 파일 읽음이 또 찍혔으니 함수가 다시 돌았다.

맞는 규칙: 앞에 꼬리표 Cache가 붙은 줄은 기억한 결과를 줄 때 다시 보여 준 로그입니다(2절). 함수가 돈 줄은 꼬리표가 없습니다.

틀린 생각: 코드를 고쳐 저장한 바로 뒤 목록이 파일을 다시 읽었으니, 'use cache'가 걸리지 않는다.

맞는 규칙: 개발 서버는 쪽이 쓰는 코드 파일을 고쳐 저장하면 기억해 둔 것을 지웁니다. 저장한 뒤 목록을 한 번 열어 기억시킨 다음부터 봅니다(해 보기).

확인 문제

문제 1. getRecipes 몸의 cacheTag('recipes') 줄이 하는 일은 무엇일까요?

  • ① 기억한 값에 이름 recipes를 붙여, 지울 때 그 이름으로 부르게 한다
  • ② 한 시간쯤 기억하게 한다
  • ③ 함수 결과를 껍데기에 넣는다
정답

①입니다. 이름은 기억을 지울 때 쓰고, 지우는 길은 단원 6에서 봅니다.

  • ② 얼마나 기억할지는 cacheLife('hours')가 정합니다.
  • ③ 결과를 기억하게 하는 것은 'use cache'입니다. 빌드가 그 결과로 껍데기를 그립니다.

문제 2. 개발 서버에서 'use cache'를 단 getRecipes를 쓰는 목록을 두 번 열었습니다. 두 번째 요청 뒤 터미널에 새로 찍힌 Cache 레시피 파일 읽음은 무엇일까요?

  • ① getRecipes가 다시 돌며 찍은 로그
  • ② 기억해 둔 결과를 주며 다시 보여 준 로그
  • ③ 기억이 지워졌다는 알림
정답

②입니다. 개발 판은 기억해 둔 결과를 줄 때 처음 돌며 찍은 로그를 꼬리표 Cache를 붙여 다시 보여 줍니다.

  • ① 함수가 다시 돌면 꼬리표 없는 레시피 파일 읽음이 찍힙니다.
  • ③ 기억이 지워진 뒤의 요청은 함수를 다시 돌려 꼬리표 없는 줄을 찍습니다.

문제 3. 배포 판으로 빌드했더니 경로 표의 /stats 줄이 ○에 1h · 1d였습니다. 이 쪽의 받은 HTML에 드는 것은 무엇일까요?

  • ① 세는 중과 구멍 표시 B:0
  • ② 통계만 — 수는 브라우저가 센다
  • ③ 모두 4개 — 빌드 때 껍데기에 들었다
정답

③입니다. 빌드가 기억된 getRecipes의 결과를 기다려 Count까지 그렸습니다. ○는 쪽 전체를 빌드 때 그렸다는 표시입니다.

  • ① 구멍이 있으면 ◐입니다.
  • ② Count도 빌드 때 그려집니다. 받은 HTML에 수가 이미 있습니다.
이 레슨에서 바꾼 파일

lib/recipes.ts — getRecipes에 'use cache' · cacheLife('hours') · cacheTag('recipes')와 로그 한 줄을 더함

lib/recipes.ts
import {
  readFile,
} from 'node:fs/promises';
import {
  cacheLife,
  cacheTag,
} from 'next/cache';

export interface Recipe {
  id: string;
  title: string;
  category: string;
  minutes: number;
  ingredients: string[];
  favorite: boolean;
}

export const categories = [
  '한식',
  '양식',
  '일식',
  '중식',
  '디저트',
];

function isRecipe(
  v: unknown,
): v is Recipe {
  return (
    typeof v === 'object' &&
    v !== null &&
    'id' in v &&
    'title' in v &&
    'category' in v &&
    'minutes' in v &&
    'ingredients' in v &&
    'favorite' in v &&
    typeof v.id === 'string' &&
    typeof v.title ===
      'string' &&
    typeof v.category ===
      'string' &&
    typeof v.minutes ===
      'number' &&
    Array.isArray(
      v.ingredients,
    ) &&
    typeof v.favorite ===
      'boolean'
  );
}

// 1. 함수 머리에 'use cache'
export const getRecipes =
  async () => {
    'use cache';
    // 2. cacheLife로 얼마나
    cacheLife('hours');
    // 3. cacheTag로 이름 붙이기
    cacheTag('recipes');
    console.log(
      '레시피 파일 읽음',
    );
    const text = await readFile(
      'data/recipes.json',
      'utf8',
    );
    const data: unknown =
      JSON.parse(text);
    return Array.isArray(data)
      ? data.filter(isRecipe)
      : [];
  };

export const getRecipe =
  async (id: string) => {
    const list =
      await getRecipes();
    return list.find(
      (r) => r.id === id,
    );
  };

끝까지 내려오면 저절로 표시됩니다. 이 기기에만 저장합니다.

Next.js 목차로