본문으로 건너뛰기

인자가 열쇠다

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

목차

'use cache'는 인자를 받는 함수에도 달 수 있습니다. 이 레슨은 자세히 쪽이 쓰는 getRecipe(id)에 'use cache'를 달아 인자 id가 기억에 어떻게 쓰이는지 서버 터미널로 세고, 요청 때 값(cookies())을 기억하는 함수와 함께 쓰는 자리를 봅니다.

지금 getRecipe는 기억된 getRecipes를 부르고, 받은 목록에서 id가 맞는 레시피를 찾습니다. getRecipe 자신도 기억하게 하면 'r1'로 부른 결과와 'r3'로 부른 결과는 어떻게 될까요?

1getRecipe에도 'use cache'

개발 서버를 켜 둔 채 따라 합니다. lib/recipes.ts의 getRecipe 몸 맨 앞에 getRecipes와 같은 세 줄을 두고, 로그 한 줄을 더합니다. 로그 글은 getRecipes의 레시피 파일 읽음과 다르게 하고, 받은 id도 찍습니다.

lib/recipes.ts
…
export const getRecipe =
  async (id: string) => {
    'use cache';
    cacheLife('hours');
    cacheTag('recipes');
    console.log(
      '레시피 하나 읽음',
      id,
    );
    const list =
      await getRecipes();
…

저장하고 주소 칸에 /recipes/r1 → /recipes/r3 → /recipes/r1 차례로 쳐서 엽니다.

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) => {
    'use cache';
    cacheLife('hours');
    cacheTag('recipes');
    console.log(
      '레시피 하나 읽음',
      id,
    );
    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 255ms
✓ Running next.config.ts took 1254ms
- Cache Components enabled
- Partial Prefetching enabled

레시피 파일 읽음
 Cache  레시피 파일 읽음
레시피 하나 읽음 r1
레시피 파일 읽음
 Cache  레시피 하나 읽음 r1
 Cache  레시피 파일 읽음
 Cache  레시피 파일 읽음
 GET /recipes/r1 200 in 453ms (next.js: 75ms, generate-params: 229ms, application-code: 149ms)
 Cache  레시피 하나 읽음 r1
 Cache  레시피 파일 읽음
 Cache  레시피 하나 읽음 r1
 Cache  레시피 파일 읽음
레시피 하나 읽음 r3
 Cache  레시피 하나 읽음 r3
 Cache  레시피 파일 읽음
 Cache  레시피 파일 읽음
 GET /recipes/r3 200 in 38ms (next.js: 0.9ms, generate-params: 1.7ms, application-code: 36ms)
 Cache  레시피 하나 읽음 r3
 Cache  레시피 파일 읽음
 Cache  레시피 하나 읽음 r3
 Cache  레시피 파일 읽음
레시피 파일 읽음
 Cache  레시피 파일 읽음
 Cache  레시피 하나 읽음 r1
 Cache  레시피 파일 읽음
 GET /recipes/r1 200 in 25ms (next.js: 0.8ms, generate-params: 1.6ms, application-code: 23ms)
 Cache  레시피 하나 읽음 r1
 Cache  레시피 파일 읽음
레시피 파일 읽음
 Cache  레시피 파일 읽음

이번에 새로 찍힌 줄 가운데 꼬리표 없는 레시피 하나 읽음은 r1과 r3을 처음 열 때의 두 줄입니다. 셋째로 다시 연 r1에서는 getRecipe가 돌지 않고 기억한 결과를 꺼내, 그 로그가 Cache가 붙은 줄로만 다시 보입니다.

꼬리표 없는 레시피 파일 읽음도 섞여 찍힙니다. 개발 서버는 이 쪽을 열 때마다 generateStaticParams도 부르고(Next.js 문서 generateStaticParams — 'During next dev, generateStaticParams will be called when you navigate to a route'), 그 안에서 getRecipes()를 부릅니다. 이 부름은 개발 서버가 따로 띄운 일꾼(worker)에서 하고, 끝나면 그 일꾼을 닫습니다(Next.js 소스 server/dev/next-dev-server.js — 'we don't re-use workers so destroy the used one'). 그곳의 기억은 늘 비어 있어, 기억된 getRecipes도 그때마다 돌아 꼬리표 없는 줄을 찍습니다. 쪽을 그리는 일과 따로 돌아, 그 줄이 찍히는 자리도 쪽마다 다릅니다. 그래서 getRecipe가 돌았는지는 꼬리표 없는 레시피 하나 읽음 줄로만 셉니다.

2기억을 찾는 열쇠

'use cache'는 함수와 인자를 묶어 열쇠로 삼고, 기억을 그 열쇠로 찾습니다(Next.js 문서 use cache 'Cache keys' — 빌드 · 함수 · 넘긴 인자 · 개발 판의 고친 코드 표시). getRecipe('r1')과 getRecipe('r3')은 열쇠가 달라 따로 기억되고, 다시 'r1'로 부르면 처음 기억한 것을 꺼냅니다. 인자가 없는 getRecipes는 어느 쪽에서 불러도 열쇠가 하나입니다.

Next.js 규칙 7 넓힘. 인자가 다른 부름은 따로 기억합니다. 같은 인자로 다시 부를 때만 기억한 결과를 줍니다.

열쇠에는 넘긴 인자만 드는 것이 아닙니다. 감싼 함수 안에서 'use cache' 함수를 만들어 바깥 변수를 쓰면, 그 변수도 잡혀서 인자처럼 열쇠에 듭니다(같은 문서 — 'variables from outer scopes … are automatically captured and bound as arguments').

목록 쪽은 검색어를 getRecipes에 넘기지 않습니다. 목록 하나를 기억해 두고, 거르기는 바깥의 RecipeList가 합니다. getRecipes(q)처럼 검색어를 인자로 넘겨 그 안에서 거르면, 검색어마다 열쇠가 생겨 거의 같은 목록을 검색어 수만큼 따로 기억합니다.

해 보기 — 'use cache' 안에서 cookies() 읽기

쿠키(cookie)는 브라우저가 요청마다 실어 보내는 작은 값이고, 서버 컴포넌트에서는 next/headers의 cookies()로 읽습니다. 쿠키는 요청 때만 아는 값입니다. 첫 쪽에 '최근 본 레시피'를 보이려 합니다. 쿠키 last에 든 id로 찾고, 쿠키가 없으면 r1을 씁니다. 찾는 일을 getLast로 묶어 'use cache'를 답니다.

app/page.tsx
…
// 최근 본 레시피 — 쿠키 last의 id
const getLast = async () => {
  'use cache';
  const jar = await cookies();
  const id =
    jar.get('last')?.value ??
    'r1';
  return getRecipe(id);
};
…

Last가 getLast()의 결과로 최근 본 레시피: … 한 줄을 그리고, Home은 Last를 <Suspense>로 감싸 즐겨찾기 위에 둡니다. import는 @/lib/recipes에서 getRecipe도 가져오고, next/headers의 cookies를 더합니다.

바꾼 app/page.tsx 전체

아래는 바꾼 app/page.tsx 전체입니다.

app/page.tsx
import {
  Suspense,
} from 'react';
import {
  getRecipe,
  getRecipes,
} from '@/lib/recipes';
import {
  cookies,
} from 'next/headers';

const wait = (ms: number) =>
  new Promise((r) => {
    setTimeout(r, ms);
  });

// 2초 걸리는 읽기라고 칩니다
const getPick = async () => {
  const recipes =
    await getRecipes();
  await wait(2000);
  return recipes[2];
};

// 1초 걸리는 읽기라고 칩니다
const getFavorites =
  async () => {
    const recipes =
      await getRecipes();
    await wait(1000);
    return recipes.filter(
      (r) => r.favorite,
    );
  };

// 1. 기다리는 일을 자식으로
async function Pick() {
  // 2. 자식에서 await로 읽기
  const pick = await getPick();
  return (
    <p>
      오늘의 추천: {pick.title}
    </p>
  );
}

async function Favorites() {
  const list =
    await getFavorites();
  const text = list
    .map((r) => r.title)
    .join(', ');
  return <p>즐겨찾기: {text}</p>;
}

// 최근 본 레시피 — 쿠키 last의 id
const getLast = async () => {
  'use cache';
  const jar = await cookies();
  const id =
    jar.get('last')?.value ??
    'r1';
  return getRecipe(id);
};

async function Last() {
  const found = await getLast();
  return (
    <p>
      최근 본 레시피:{' '}
      {found?.title}
    </p>
  );
}

// 3. 쪽에서 Suspense로 감싸기
export default function Home() {
  return (
    <>
      <h1>레시피 보관함</h1>
      <Suspense
        fallback={
          <p>추천을 고르는 중</p>
        }
      >
        <Pick />
      </Suspense>
      <Suspense
        fallback={
          <p>기록을 읽는 중</p>
        }
      >
        <Last />
      </Suspense>
      <Suspense
        fallback={
          <p>즐겨찾기를 읽는 중</p>
        }
      >
        <Favorites />
      </Suspense>
    </>
  );
}

개발 서버를 끄고 npm run build를 치면 어떻게 될까요? 고른 뒤 펼쳐 보세요. 맞혀 보기는 점수에 들지 않습니다.

  • ① 지나가고, 쿠키 값마다 따로 기억된다
  • ② /에서 멈춘다
  • ③ 지나가고, /가 ○가 된다
결과 보기

②입니다. 아래는 1절 그대로의 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) => {
    'use cache';
    cacheLife('hours');
    cacheTag('recipes');
    console.log(
      '레시피 하나 읽음',
      id,
    );
    const list =
      await getRecipes();
    return list.find(
      (r) => r.id === id,
    );
  };
실행 결과
  Creating an optimized production build ...
✓ Compiled successfully in 1838ms
  Running TypeScript ...
  Finished TypeScript in 1160ms ...
  Collecting page data using 8 workers ...
레시피 파일 읽음
✓ Collecting page data using 8 workers in 398ms
  Generating static pages using 8 workers (0/11) ...
레시피 파일 읽음
⨯ Error: Route "/": `cookies()` can't be read inside `"use cache"`. Read it outside the cached function and pass what you need as an argument.
Learn more: https://nextjs.org/docs/messages/next-request-in-use-cache
    at m (app/page.tsx:59:21)
  57 | const getLast = async () => {
  58 |   'use cache';
> 59 |   const jar = await cookies();
     |                     ^
  60 |   const id =
  61 |     jar.get('last')?.value ??
  62 |     'r1'; {
  digest: '2308026998'
}
레시피 하나 읽음 r1
레시피 하나 읽음 r3
레시피 하나 읽음 r4
레시피 하나 읽음 r2
Error: Route "/": `cookies()` can't be read inside `"use cache"`. Read it outside the cached function and pass what you need as an argument.
Learn more: https://nextjs.org/docs/messages/next-request-in-use-cache
    at m (app/page.tsx:59:21)
  57 | const getLast = async () => {
  58 |   'use cache';
> 59 |   const jar = await cookies();
     |                     ^
  60 |   const id =
  61 |     jar.get('last')?.value ??
  62 |     'r1'; {
  digest: '2308026998'
}
To get a more detailed stack trace and pinpoint the issue, try one of the following:
  - Start the app in development mode by running `next dev`, then open "/" in your browser to investigate the error.
  - Rerun the production build with `next build --debug-prerender` to generate better stack traces.
Error occurred prerendering page "/". Read more: https://nextjs.org/docs/messages/prerender-error
Export encountered an error on /page: /, exiting the build.
⨯ Next.js build worker exited with code: 1 and signal: null
exit=1

⨯ Error: Route "/":로 시작하는 줄은 'use cache' 안에서는 cookies()를 읽을 수 없으니(can't be read inside), 기억하는 함수 바깥에서 읽고 필요한 것을 인자로 넘기라는(pass what you need as an argument) 뜻입니다. 같은 오류 글이 한 번 더 찍힙니다. 코드 줄 표시는 getLast 안의 await cookies()를 가리킵니다. Next.js 문서도 기억하는 함수는 cookies() · headers() · searchParams 같은 요청 때 값을 읽을 수 없고, 바깥에서 읽어 인자로 넘기라고 적습니다(use cache 'Request-time APIs').

빌드 출력의 레시피 하나 읽음은 빌드가 자세히 쪽(/recipes/r1 ~ r4)을 미리 그리며 부른 getRecipe의 로그입니다. 빌드는 쪽 여럿을 일꾼(worker) 여럿이 나눠 그리고(using 8 workers) /에서 멈추면 곧바로 끝나서, 이 로그 줄들의 차례와 수는 빌드마다 다를 수 있습니다.

해 보기 — 바깥에서 읽어 인자로

오류 글대로 고칩니다. 쿠키는 Last에서 읽고, 꺼낸 id를 기억된 getRecipe에 인자로 넘깁니다. getLast는 지웁니다.

app/page.tsx
…
async function Last() {
  // 4. 요청 값은 바깥에서 읽어 인자로
  const jar = await cookies();
  const id =
    jar.get('last')?.value ??
    'r1';
  const found =
    await getRecipe(id);
…

고친 뒤 npm run build → npm run start로 띄워 /를 엽니다.

app/page.tsx 전체 · lib/recipes.ts · 빌드 출력 · 받은 HTML

아래는 고친 app/page.tsx 전체, 1절 그대로의 lib/recipes.ts, 빌드 출력, 배포 판 /의 받은 HTML(다듬음)입니다. 쿠키 없이 열어 r1을 씁니다.

app/page.tsx
import {
  Suspense,
} from 'react';
import {
  getRecipe,
  getRecipes,
} from '@/lib/recipes';
import {
  cookies,
} from 'next/headers';

const wait = (ms: number) =>
  new Promise((r) => {
    setTimeout(r, ms);
  });

// 2초 걸리는 읽기라고 칩니다
const getPick = async () => {
  const recipes =
    await getRecipes();
  await wait(2000);
  return recipes[2];
};

// 1초 걸리는 읽기라고 칩니다
const getFavorites =
  async () => {
    const recipes =
      await getRecipes();
    await wait(1000);
    return recipes.filter(
      (r) => r.favorite,
    );
  };

// 1. 기다리는 일을 자식으로
async function Pick() {
  // 2. 자식에서 await로 읽기
  const pick = await getPick();
  return (
    <p>
      오늘의 추천: {pick.title}
    </p>
  );
}

async function Favorites() {
  const list =
    await getFavorites();
  const text = list
    .map((r) => r.title)
    .join(', ');
  return <p>즐겨찾기: {text}</p>;
}

async function Last() {
  // 4. 요청 값은 바깥에서 읽어 인자로
  const jar = await cookies();
  const id =
    jar.get('last')?.value ??
    'r1';
  const found =
    await getRecipe(id);
  return (
    <p>
      최근 본 레시피:{' '}
      {found?.title}
    </p>
  );
}

// 3. 쪽에서 Suspense로 감싸기
export default function Home() {
  return (
    <>
      <h1>레시피 보관함</h1>
      <Suspense
        fallback={
          <p>추천을 고르는 중</p>
        }
      >
        <Pick />
      </Suspense>
      <Suspense
        fallback={
          <p>기록을 읽는 중</p>
        }
      >
        <Last />
      </Suspense>
      <Suspense
        fallback={
          <p>즐겨찾기를 읽는 중</p>
        }
      >
        <Favorites />
      </Suspense>
    </>
  );
}
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) => {
    'use cache';
    cacheLife('hours');
    cacheTag('recipes');
    console.log(
      '레시피 하나 읽음',
      id,
    );
    const list =
      await getRecipes();
    return list.find(
      (r) => r.id === id,
    );
  };
실행 결과
  Creating an optimized production build ...
✓ Compiled successfully in 1609ms
  Running TypeScript ...
  Finished TypeScript in 1294ms ...
  Collecting page data using 8 workers ...
레시피 파일 읽음
✓ Collecting page data using 8 workers in 300ms
  Generating static pages using 8 workers (0/11) ...
레시피 하나 읽음 r1
레시피 파일 읽음
레시피 하나 읽음 r2
레시피 하나 읽음 r4
레시피 하나 읽음 r3
  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 442ms
  Finalizing page optimization ...
✓ Finalizing page optimization in 13ms

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><template id="B:0"></template><p>추천을 고르는 중</p><template id="B:1"></template><p>기록을 읽는 중</p><template id="B:2"></template><p>즐겨찾기를 읽는 중</p><footer>바닥글</footer><div hidden id="S:1"><p>최근 본 레시피: 김치볶음밥</p></div><!-- 덩어리 2 · 1초 뒤 --><div hidden id="S:2"><p>즐겨찾기: 김치볶음밥, 바나나 팬케이크</p></div><!-- 덩어리 3 · 2초 뒤 --><div hidden id="S:0"><p>오늘의 추천: 계란말이</p></div>
결과 화면

빌드가 지나가고 /는 ◐입니다. cookies()는 요청 때만 아는 값이라 Last 자리는 <Suspense> 안 구멍으로 남고, 요청이 오면 최근 본 레시피: 김치볶음밥으로 채워집니다. 그 안의 getRecipe(id)는 기억된 함수라, 같은 id로 다시 부르면 기억한 결과를 줍니다(2절).

다 봤으면 배포 판을 끄고, app/page.tsx에서 Last · 그 <Suspense> · 더한 import를 지워 앞 레슨 끝 판으로 되돌린 뒤 npm run dev로 개발 서버를 다시 띄웁니다.

예제

자세히 쪽을 다른 차례로 열어 셉니다. 개발 서버를 Ctrl+C로 끄고 npm run dev로 새로 띄운 뒤, 주소 칸에 /recipes/r2 → /recipes/r4 → /recipes/r2 → /recipes/r2 차례로 쳐서 엽니다. 터미널에 새로 찍힌 줄 가운데 꼬리표 없는 레시피 하나 읽음은 몇 줄일까요? 고른 뒤 펼쳐 보세요. 맞혀 보기는 점수에 들지 않습니다.

  • ① 4줄 — 쪽을 넷 열었으니까
  • ② 1줄 — 처음 한 번만 읽으니까
  • ③ 2줄 — r2와 r4를 처음 열 때
결과 보기

③입니다. 아래는 1절 그대로의 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) => {
    'use cache';
    cacheLife('hours');
    cacheTag('recipes');
    console.log(
      '레시피 하나 읽음',
      id,
    );
    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 228ms
✓ Running next.config.ts took 1002ms
- Cache Components enabled
- Partial Prefetching enabled

레시피 파일 읽음
 Cache  레시피 파일 읽음
레시피 하나 읽음 r2
레시피 파일 읽음
 Cache  레시피 하나 읽음 r2
 Cache  레시피 파일 읽음
 Cache  레시피 파일 읽음
 GET /recipes/r2 200 in 443ms (next.js: 75ms, generate-params: 233ms, application-code: 135ms)
 Cache  레시피 하나 읽음 r2
 Cache  레시피 파일 읽음
 Cache  레시피 하나 읽음 r2
 Cache  레시피 파일 읽음
레시피 하나 읽음 r4
 Cache  레시피 하나 읽음 r4
 Cache  레시피 파일 읽음
 Cache  레시피 파일 읽음
 GET /recipes/r4 200 in 52ms (next.js: 2ms, generate-params: 4ms, application-code: 46ms)
 Cache  레시피 하나 읽음 r4
 Cache  레시피 파일 읽음
 Cache  레시피 하나 읽음 r4
 Cache  레시피 파일 읽음
레시피 파일 읽음
 Cache  레시피 파일 읽음
 Cache  레시피 하나 읽음 r2
 Cache  레시피 파일 읽음
 GET /recipes/r2 200 in 23ms (next.js: 0.9ms, generate-params: 1.5ms, application-code: 21ms)
 Cache  레시피 하나 읽음 r2
 Cache  레시피 파일 읽음
레시피 파일 읽음
 Cache  레시피 파일 읽음
 Cache  레시피 하나 읽음 r2
 Cache  레시피 파일 읽음
 GET /recipes/r2 200 in 20ms (next.js: 0.8ms, generate-params: 1.3ms, application-code: 18ms)
 Cache  레시피 하나 읽음 r2
 Cache  레시피 파일 읽음
레시피 파일 읽음
 Cache  레시피 파일 읽음

꼬리표 없는 레시피 하나 읽음은 r2와 r4를 처음 열 때의 두 줄입니다. 셋째 · 넷째로 연 r2는 기억한 결과를 꺼내, Cache가 붙은 줄만 찍혔습니다. 꼬리표 없는 레시피 파일 읽음은 1절처럼 섞여 찍히는 줄이라 세지 않습니다.

자주 틀리는 곳

틀린 생각: 'use cache' 함수가 바깥 변수를 쓰면, 그 변수는 열쇠에 들지 않는다.

맞는 규칙: 감싼 함수 안에서 만든 'use cache' 함수가 쓰는 바깥 변수는 잡혀서 인자처럼 열쇠에 듭니다(Next.js 문서 use cache 'Cache keys'). 값이 다르면 따로 기억합니다.

틀린 생각: 검색어를 getRecipes(q)로 넘겨 그 안에서 거르면 기억을 잘 쓰는 것이다.

맞는 규칙: 검색어마다 열쇠가 새로 생깁니다. 목록 하나를 기억해 두고 바깥에서 거르면 열쇠는 하나입니다(2절).

틀린 생각: 자세히 쪽을 넷 열고 터미널의 레시피 하나 읽음 줄을 모두 세면, 함수가 돈 수다.

맞는 규칙: 앞에 꼬리표 Cache가 붙은 줄은 다시 보여 준 로그입니다. 함수가 돈 수는 꼬리표 없는 줄만 셉니다(예제).

확인 문제

문제 1. (개발 판 — npm run dev를 새로 띄운 뒤) 몇 분 안에 이어서 /recipes/r1 → /recipes/r1 → /recipes/r3 차례로 열면, 꼬리표 없는 레시피 하나 읽음 줄은 몇 줄일까요?

  • ① 1줄
  • ② 2줄
  • ③ 3줄
정답

②입니다. 'r1'과 'r3'을 처음 부를 때 한 줄씩입니다. 둘째 'r1'은 기억한 결과를 줍니다.

  • ① 열쇠가 다른 'r3'은 따로 기억되어, 처음 부를 때 함수가 돕니다.
  • ③ 같은 'r1'로 다시 부르면 함수가 돌지 않습니다.

문제 2. 목록 쪽이 검색어를 getRecipes(q)처럼 인자로 넘기고, 'use cache'를 단 getRecipes 안에서 거르게 바꿨습니다. /recipes?q=밥과 /recipes?q=파스타를 열면 기억은 어떻게 될까요?

  • ① 검색어마다 따로 기억된다
  • ② 하나를 같이 쓴다 — 같은 함수니까
  • ③ 기억하지 않는다 — 검색어는 요청 때 값이니까
정답

①입니다. 넘긴 인자가 열쇠에 드니, 검색어가 다르면 열쇠도 다릅니다. 그래서 목록 하나를 기억해 두고 바깥에서 거릅니다(2절).

  • ② 함수가 같아도 인자가 다르면 따로 기억합니다.
  • ③ 검색어를 바깥에서 꺼내 인자로 넘겼으니 기억합니다. 멈추는 것은 요청 때 값을 'use cache' 안에서 직접 읽을 때입니다.

문제 3. 고친 Last처럼 쿠키에서 꺼낸 id를 getRecipe(id)에 넘깁니다. 이 꼴을 하위 목표로 말하면 무엇일까요?

  • ① 함수 머리에 'use cache'
  • ② cacheTag로 이름 붙이기
  • ③ 요청 값은 바깥에서 읽어 인자로
정답

③입니다. 요청 때만 아는 값(쿠키)은 기억하는 함수 바깥에서 읽고, 필요한 것만 인자로 넘깁니다.

  • ① getRecipe의 'use cache'는 1절에서 이미 달았습니다.
  • ② cacheTag로 붙이는 이름은 기억을 지울 때 쓰는 것입니다.
이 레슨에서 바꾼 파일

lib/recipes.ts — getRecipe에도 '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) => {
    'use cache';
    cacheLife('hours');
    cacheTag('recipes');
    console.log(
      '레시피 하나 읽음',
      id,
    );
    const list =
      await getRecipes();
    return list.find(
      (r) => r.id === id,
    );
  };

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

Next.js 목차로