본문으로 건너뛰기

그때그때 다른 값

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

목차

불안정한 값(unstable value)은 Math.random()이나 new Date()처럼 부를 때마다 달라질 수 있는 값입니다. 이 레슨은 첫 쪽의 '오늘의 추천'을 Math.random()으로 고르게 바꿔 빌드가 이 값을 어떻게 다루는지 보고, 추천을 고르는 때를 정하는 세 길을 견줍니다.

지금 추천은 늘 recipes[2], 계란말이입니다. 넷 가운데 하나를 골라 보이고 싶습니다. 브라우저에서만 그리는 리액트 판이라면 고르는 Math.random() 한 줄을 effect나 이벤트에 두면 됩니다. 렌더 중에 고르면 리액트 규칙 1에 어긋납니다(순수한 컴포넌트 — 두 번 불러도 같게). 빌드가 쪽을 미리 그리는 Next.js에서는 그 한 줄이 언제 돌까요?

Math.random()은 부를 때마다 0 이상 1 미만의 수를 다르게 줍니다. 레시피 수를 곱해 Math.floor()로 소수점 아래를 내리면 0부터 3 사이의 번호가 됩니다(JS 다시 보기: 사칙 계산과 나머지 3절).

1Math.random()으로 고르기

app/page.tsx의 getPick이 레시피를 읽은 뒤 번호를 무작위로 고르게 바꿉니다. return도 고른 번호의 레시피로 바꿉니다.

app/page.tsx
…
const getPick = async () => {
  const recipes =
    await getRecipes();
  const at = Math.floor(
    Math.random() *
      recipes.length,
  );
  await wait(2000);
  return recipes[at];
};
…

개발 서버를 Ctrl+C로 끄고 npm run build를 칩니다.

바꾼 app/page.tsx 전체 · 빌드 출력

아래는 바꾼 app/page.tsx 전체와 빌드 출력입니다.

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

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

// 2초 걸리는 읽기라고 칩니다
const getPick = async () => {
  const recipes =
    await getRecipes();
  const at = Math.floor(
    Math.random() *
      recipes.length,
  );
  await wait(2000);
  return recipes[at];
};

// 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>;
}

// 3. 쪽에서 Suspense로 감싸기
export default function Home() {
  return (
    <>
      <h1>레시피 보관함</h1>
      <Suspense
        fallback={
          <p>추천을 고르는 중</p>
        }
      >
        <Pick />
      </Suspense>
      <Suspense
        fallback={
          <p>즐겨찾기를 읽는 중</p>
        }
      >
        <Favorites />
      </Suspense>
    </>
  );
}
  Creating an optimized production build ...
✓ Compiled successfully in 1555ms
  Running TypeScript ...
  Finished TypeScript in 1109ms ...
  Collecting page data using 8 workers ...
레시피 파일 읽음
✓ Collecting page data using 8 workers in 329ms
  Generating static pages using 8 workers (0/11) ...
레시피 파일 읽음
레시피 하나 읽음 r1
레시피 하나 읽음 r2
레시피 하나 읽음 r4
레시피 하나 읽음 r3
Error: Route "/": Next.js encountered the unstable value `Math.random()` while prerendering.

This value can change between renders, so it must be either prerendered or computed later.

Ways to fix this:
  - [dynamic] Render at request time by adding a dynamic data access (e.g. `await connection()`) before this call
  - [cache] Prerender and cache the value with `"use cache"`
  - [client] Render the value on the client with `"use client"`

Learn more: https://nextjs.org/docs/messages/blocking-prerender-random
    at f (app/page.tsx:18:10)
    at async h (app/page.tsx:39:16)
  16 |     await getRecipes();
  17 |   const at = Math.floor(
> 18 |     Math.random() *
     |          ^
  19 |       recipes.length,
  20 |   );
  21 |   await wait(2000);
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 "/":로 시작하는 줄은 /를 미리 그리다(while prerendering) 불안정한 값 Math.random()을 만났다는 뜻입니다. 둘째 문단은 이 값이 그릴 때마다 달라질 수 있어, 미리 그려 굳히든지 나중에 계산하든지 하나여야 한다고(it must be either prerendered or computed later) 말합니다. 코드 줄 표시는 getPick 안의 Math.random()을 가리킵니다.

빌드가 이 줄까지 온 것은 getRecipes가 기억된 함수라서입니다. 빌드는 기억해 둘 읽기를 먼저 마치고 그립니다(빌드가 미리 그린 것 자주 틀리는 곳). 단원 4 판처럼 기억하지 않는 getRecipes였다면, 빌드는 파일 읽기에서 그 자리를 구멍으로 남기고 이 줄까지 오지 않습니다.

2값을 다루는 세 길

오류 글의 Ways to fix this: 아래 세 줄이 고치는 길입니다.

  • [dynamic] — 그 줄 앞에 await connection() 같은 요청 때 일을 두어, 요청이 올 때 그립니다(Render at request time).
  • [cache] — 'use cache'로 미리 그려 기억합니다(Prerender and cache the value).
  • [client] — 'use client' 컴포넌트에서 그립니다(Render the value on the client).

세 길은 추천이 골라지는 때가 다릅니다. [cache] 길은 한 번 고른 추천을 기억해, 기억하는 동안 모두에게 같은 추천을 줍니다. 3절에서 추천에 맞는 길을 고르고, [client] 길은 해 보기에서 따라가 봅니다.

3추천을 요청마다 서버에서 고르려면

추천을 요청마다 서버에서 새로 골라 받은 HTML에 싣고 싶습니다. 세 길 가운데 어느 것일까요? 고른 뒤 펼쳐 보세요. 맞혀 보기는 점수에 들지 않습니다.

  • ① [cache]
  • ② [client]
  • ③ [dynamic]
결과 보기

③입니다. next/server의 connection()을 getPick 맨 앞에서 기다립니다. connection()은 요청이 올 때까지 그리기를 멈추게 하는 함수입니다(Next.js 문서 connection — 'prerendering stops here'). 아래는 고친 app/page.tsx 전체와 빌드 출력입니다.

app/page.tsx
import {
  Suspense,
} from 'react';
import {
  getRecipes,
} from '@/lib/recipes';
import {
  connection,
} from 'next/server';

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

// 2초 걸리는 읽기라고 칩니다
const getPick = async () => {
  await connection();
  const recipes =
    await getRecipes();
  const at = Math.floor(
    Math.random() *
      recipes.length,
  );
  await wait(2000);
  return recipes[at];
};

// 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>;
}

// 3. 쪽에서 Suspense로 감싸기
export default function Home() {
  return (
    <>
      <h1>레시피 보관함</h1>
      <Suspense
        fallback={
          <p>추천을 고르는 중</p>
        }
      >
        <Pick />
      </Suspense>
      <Suspense
        fallback={
          <p>즐겨찾기를 읽는 중</p>
        }
      >
        <Favorites />
      </Suspense>
    </>
  );
}
  Creating an optimized production build ...
✓ Compiled successfully in 1412ms
  Running TypeScript ...
  Finished TypeScript in 1034ms ...
  Collecting page data using 8 workers ...
레시피 파일 읽음
✓ Collecting page data using 8 workers in 273ms
  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 473ms
  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

빌드가 지나가고 /는 ◐입니다. 빌드는 connection()에서 그 자리 그리기를 멈추고 fallback 추천을 고르는 중을 껍데기에 둡니다. Math.random()은 요청이 온 뒤에 돌아, 새로 고칠 때마다 추천이 바뀔 수 있습니다. 넷 가운데 하나를 고르니 같은 것이 이어 나올 수도 있습니다.

해 보기 — 클라이언트 컴포넌트에서 고르면

[client] 길을 따라, 고르는 일을 클라이언트 컴포넌트로 옮겨 봅니다. 레시피 이름 둘을 props로 받아 그 가운데 하나를 Math.random()으로 고르는 PickClient를 새로 만들고, 3절 판 Home의 <h1> 아래에 둡니다.

새 파일 components/PickClient.tsx
components/PickClient.tsx
'use client';

function PickClient({
  titles,
}: {
  titles: string[];
}) {
  const at = Math.floor(
    Math.random() *
      titles.length,
  );
  return (
    <p>
      골라 봄: {titles[at]}
    </p>
  );
}

export default PickClient;
app/page.tsx
…
import PickClient from
  '@/components/PickClient';
…
      <h1>레시피 보관함</h1>
      <PickClient
        titles={[
          '김치볶음밥',
          '계란말이',
        ]}
      />
…

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

  • ① 지나가고, 브라우저가 열 때마다 고른다
  • ② 지나가고, 빌드 때 고른 하나가 껍데기에 굳는다
  • ③ /에서 멈춘다
결과 보기

③입니다. 아래는 PickClient를 둔 app/page.tsx 전체와 빌드 출력입니다.

app/page.tsx
import {
  Suspense,
} from 'react';
import {
  getRecipes,
} from '@/lib/recipes';
import {
  connection,
} from 'next/server';
import PickClient from
  '@/components/PickClient';

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

// 2초 걸리는 읽기라고 칩니다
const getPick = async () => {
  await connection();
  const recipes =
    await getRecipes();
  const at = Math.floor(
    Math.random() *
      recipes.length,
  );
  await wait(2000);
  return recipes[at];
};

// 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>;
}

// 3. 쪽에서 Suspense로 감싸기
export default function Home() {
  return (
    <>
      <h1>레시피 보관함</h1>
      <PickClient
        titles={[
          '김치볶음밥',
          '계란말이',
        ]}
      />
      <Suspense
        fallback={
          <p>추천을 고르는 중</p>
        }
      >
        <Pick />
      </Suspense>
      <Suspense
        fallback={
          <p>즐겨찾기를 읽는 중</p>
        }
      >
        <Favorites />
      </Suspense>
    </>
  );
}
  Creating an optimized production build ...
✓ Compiled successfully in 1923ms
  Running TypeScript ...
  Finished TypeScript in 1346ms ...
  Collecting page data using 8 workers ...
레시피 파일 읽음
✓ Collecting page data using 8 workers in 365ms
  Generating static pages using 8 workers (0/11) ...
레시피 하나 읽음 r1
레시피 파일 읽음
레시피 하나 읽음 r2
레시피 하나 읽음 r3
레시피 하나 읽음 r4
Error: Route "/": Next.js encountered the unstable value `Math.random()` in a Client Component.

This value would be evaluated during the prerender, instead of recomputed on each visit.

Ways to fix this:
  - [stream] Wrap the Client Component in `<Suspense fallback={...}>`
  - [defer] Move the read into a `useEffect` or event handler

Learn more: https://nextjs.org/docs/messages/blocking-prerender-random-client
    at <unknown> (components/PickClient.tsx:9:10)
   7 | }) {
   8 |   const at = Math.floor(
>  9 |     Math.random() *
     |          ^
  10 |       titles.length,
  11 |   );
  12 |   return (
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 "/":로 시작하는 줄은 클라이언트 컴포넌트에서(in a Client Component) Math.random()을 만났다는 뜻입니다. 둘째 문단은 이 값이 요청마다 새로 계산되지 않고 미리 그릴 때 한 번 계산된다고(would be evaluated during the prerender, instead of recomputed on each visit) 말합니다. 클라이언트 컴포넌트도 빌드 때 한 번 그려 껍데기에 들기 때문입니다. 코드 줄 표시는 PickClient 안의 Math.random()을 가리킵니다.

이번 오류 글이 내미는 길은 둘입니다. [stream]은 그 컴포넌트를 <Suspense>로 감싸는 길이고, [defer]는 고르는 일을 useEffect나 이벤트 처리기로 옮기는 길입니다. 브라우저에서만 고르려면 [defer]처럼 effect 안에서 고릅니다. 하이드레이션 오류의 해 보기에서 갈래를 effect 안으로 옮긴 그 길입니다.

다 봤으면 components/PickClient.tsx⁠를 지우고, app/page.tsx에서 PickClient import와 <PickClient … />를 지워 3절 판으로 되돌립니다.

해 보기 — 날짜 한 줄을 넣으면

첫 쪽 머리 아래에 오늘 날짜를 찍으려고, 3절 판 Home의 <h1> 아래에 한 줄을 넣습니다. new Date().getDate()는 오늘이 며칠인지를 줍니다.

app/page.tsx
…
      <h1>레시피 보관함</h1>
      <p>
        오늘은{' '}
        {new Date().getDate()}일
      </p>
…

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

  • ① /에서 멈춘다 — 날짜도 그릴 때마다 달라질 수 있는 값이다
  • ② 지나간다 — 날짜는 하루 동안 같으니까
  • ③ 지나가고, 날짜 줄은 요청 때 채운다
결과 보기

①입니다. 아래는 날짜 줄을 넣은 app/page.tsx 전체와 빌드 출력입니다.

app/page.tsx
import {
  Suspense,
} from 'react';
import {
  getRecipes,
} from '@/lib/recipes';
import {
  connection,
} from 'next/server';

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

// 2초 걸리는 읽기라고 칩니다
const getPick = async () => {
  await connection();
  const recipes =
    await getRecipes();
  const at = Math.floor(
    Math.random() *
      recipes.length,
  );
  await wait(2000);
  return recipes[at];
};

// 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>;
}

// 3. 쪽에서 Suspense로 감싸기
export default function Home() {
  return (
    <>
      <h1>레시피 보관함</h1>
      <p>
        오늘은{' '}
        {new Date().getDate()}일
      </p>
      <Suspense
        fallback={
          <p>추천을 고르는 중</p>
        }
      >
        <Pick />
      </Suspense>
      <Suspense
        fallback={
          <p>즐겨찾기를 읽는 중</p>
        }
      >
        <Favorites />
      </Suspense>
    </>
  );
}
  Creating an optimized production build ...
✓ Compiled successfully in 2.8s
  Running TypeScript ...
  Finished TypeScript in 1498ms ...
  Collecting page data using 8 workers ...
레시피 파일 읽음
✓ Collecting page data using 8 workers in 563ms
  Generating static pages using 8 workers (0/11) ...
레시피 파일 읽음
레시피 하나 읽음 r1
레시피 하나 읽음 r2
레시피 하나 읽음 r3
레시피 하나 읽음 r4
Error: Route "/": Next.js encountered the unstable value `new Date()` while prerendering.

This value can change between renders, so it must be either prerendered or computed later.

Ways to fix this:
  - [dynamic] Render at request time by adding a dynamic data access (e.g. `await connection()`) before this call
  - [cache] Prerender and cache the value with `"use cache"`
  - [client] Render the value on the client with `"use client"`
  - [measure] If the value is for telemetry, use a timing API such as `performance.now()`

Learn more: https://nextjs.org/docs/messages/blocking-prerender-current-time
    at <unknown> (app/page.tsx:67:10)
  65 |       <p>
  66 |         오늘은{' '}
> 67 |         {new Date().getDate()}일
     |          ^
  68 |       </p>
  69 |       <Suspense
  70 |         fallback={
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 "/":로 시작하는 줄은 1절과 같은 꼴이고, 이번에 만난 값은 new Date()입니다. 빌드는 지금 시각도 그릴 때마다 달라질 수 있는 값으로 봅니다. 고치는 길은 넷입니다. 1절 오류 글의 세 길에 [measure]가 더 있는데, 그 값을 재기(telemetry)에 쓰는 것이면 performance.now() 같은 시간 재기 API를 쓰라는 길입니다. 날짜를 보이려는 이 줄에는 맞지 않습니다. 코드 줄 표시는 Home 안의 new Date()를 가리킵니다.

다 봤으면 날짜 줄 넷을 지워 3절 판으로 되돌립니다.

예제

3절에서는 await connection()을 getPick 맨 앞에 두었습니다. [dynamic] 줄은 불안정한 값을 부르기 앞(before this call)이라고만 합니다. getRecipes()를 기다린 뒤, Math.random() 바로 앞으로 옮기면 빌드는 어떻게 될까요?

app/page.tsx
…
const getPick = async () => {
  const recipes =
    await getRecipes();
  await connection();
  const at = Math.floor(
    Math.random() *
      recipes.length,
  );
  await wait(2000);
  return recipes[at];
};
…

고른 뒤 펼쳐 보세요. 맞혀 보기는 점수에 들지 않습니다.

  • ① /에서 멈춘다 — connection()보다 getRecipes()를 먼저 기다리니까
  • ② 지나가고, /는 ◐다
  • ③ 지나가고, 추천이 빌드 때 껍데기에 굳는다
결과 보기

②입니다. 아래는 옮긴 app/page.tsx 전체와 빌드 출력입니다.

app/page.tsx
import {
  Suspense,
} from 'react';
import {
  getRecipes,
} from '@/lib/recipes';
import {
  connection,
} from 'next/server';

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

// 2초 걸리는 읽기라고 칩니다
const getPick = async () => {
  const recipes =
    await getRecipes();
  await connection();
  const at = Math.floor(
    Math.random() *
      recipes.length,
  );
  await wait(2000);
  return recipes[at];
};

// 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>;
}

// 3. 쪽에서 Suspense로 감싸기
export default function Home() {
  return (
    <>
      <h1>레시피 보관함</h1>
      <Suspense
        fallback={
          <p>추천을 고르는 중</p>
        }
      >
        <Pick />
      </Suspense>
      <Suspense
        fallback={
          <p>즐겨찾기를 읽는 중</p>
        }
      >
        <Favorites />
      </Suspense>
    </>
  );
}
  Creating an optimized production build ...
✓ Compiled successfully in 2.1s
  Running TypeScript ...
  Finished TypeScript in 1801ms ...
  Collecting page data using 8 workers ...
레시피 파일 읽음
✓ Collecting page data using 8 workers in 505ms
  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 519ms
  Finalizing page optimization ...
✓ Finalizing page optimization in 12ms

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

빌드는 기억된 getRecipes의 결과를 받은 뒤 connection()에서 멈추고, 추천 자리를 구멍으로 남깁니다. Math.random()은 그 뒤라 요청이 올 때 돕니다. connection()이 불안정한 값보다 앞에만 있으면 됩니다. 이 레슨을 마친 getPick은 이 판입니다.

자주 틀리는 곳

틀린 생각: await connection()은 쪽 어디에 두어도 그 아래만 요청 때로 미룬다.

맞는 규칙: <Suspense> 밖에서 connection()을 기다리면 쪽을 미리 그리지 못하게 막아(prevents the route from being prerendered), 빌드가 다른 오류로 멈춥니다. Home 맨 앞에 두면 'encountered uncached or runtime data during prerendering' 오류가 나고, 오류 글은 그 자리를 <Suspense>로 감싸라고([stream]) 합니다. getPick처럼 <Suspense> 안 자식이 기다리는 자리에 둡니다.

틀린 생각: new Date()는 하루 동안 같으니 미리 그려도 된다.

맞는 규칙: 빌드는 지금 시각도 그릴 때마다 달라질 수 있는 값으로 봅니다(해 보기 — 날짜 한 줄을 넣으면). 추천과 같은 길로 고칩니다.

틀린 생각: 'use client' 컴포넌트는 브라우저에서 도니, 렌더 중에 Math.random()을 불러도 빌드와 상관없다.

맞는 규칙: 클라이언트 컴포넌트도 빌드 때 한 번 그려집니다. 껍데기에 드는 자리(<Suspense> 밖)에서 렌더 중에 부르면 빌드가 멈춥니다(해 보기 — 클라이언트 컴포넌트에서 고르면).

확인 문제

문제 1. 빌드가 Route "/"에서 Math.random()을 만났다는 오류(encountered the unstable value … while prerendering)로 멈췄습니다. 이 오류가 말하는 것은 무엇일까요?

  • ① 미리 그리는 중에 그릴 때마다 달라질 수 있는 값을 만났다
  • ② Math.random()은 서버에서 부를 수 없다
  • ③ /에 <Suspense>가 없다
정답

①입니다. 그 값은 미리 그려 굳히든지 나중에 계산하든지 하나여야 합니다.

  • ② [dynamic] 길처럼 요청 때 서버에서 부르면 됩니다.
  • ③ 추천 자리는 이미 <Suspense> 안입니다. 멈춘 것은 미리 그리는 중에 값을 만나서입니다.

문제 2. getPick 맨 앞에 await connection()을 둔 뒤 빌드 출력 경로 표의 / 줄은 무엇일까요?

  • ① ○ / — 쪽 전체를 빌드 때 그렸다
  • ② ◐ / — 추천 자리는 요청 때 채운다
  • ③ 줄이 없다 — 빌드가 멈췄다
정답

②입니다. 빌드는 connection()에서 그 자리를 멈추고 fallback을 껍데기에 둡니다(3절).

  • ① 추천 자리가 구멍으로 남아 ○가 아닙니다.
  • ③ connection() 뒤의 Math.random()은 요청 때 돌아 빌드를 멈추지 않습니다.

문제 3. 추천을 하루쯤 그대로 두고, 그동안은 모두에게 같은 추천을 보이려 합니다. 세 길 가운데 맞는 것은 무엇일까요?

  • ① [client] — 브라우저가 고른다
  • ② [dynamic] — 요청 때 고른다
  • ③ [cache] — 고른 것을 기억한다
정답

③입니다. 'use cache'로 고른 결과를 기억하면, 기억하는 동안 모두에게 같은 추천이 갑니다. 하루쯤이라면 revalidate가 1일인 cacheLife('days')가 맞습니다(얼마나 기억하나 1절의 프로필 표).

  • ① 브라우저마다 따로 골라, 사람마다 다른 추천이 됩니다.
  • ② 요청마다 새로 골라, 새로 고칠 때마다 바뀔 수 있습니다.

단원 5를 마쳤습니다. 빌드가 쪽마다 껍데기를 그려 두는 것을 보고, 읽은 결과를 'use cache'로 기억시켜 껍데기에 넣었습니다. 기억한 목록은 데이터 파일을 고쳐도 그대로입니다. 레시피를 더하고 기억을 지우는 일은 단원 6에서 봅니다.

이 레슨에서 바꾼 파일

app/page.tsx — getPick이 getRecipes() 뒤 await connection()을 기다리고 Math.random()으로 추천을 고름

app/page.tsx
import {
  Suspense,
} from 'react';
import {
  getRecipes,
} from '@/lib/recipes';
import {
  connection,
} from 'next/server';

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

// 2초 걸리는 읽기라고 칩니다
const getPick = async () => {
  const recipes =
    await getRecipes();
  await connection();
  const at = Math.floor(
    Math.random() *
      recipes.length,
  );
  await wait(2000);
  return recipes[at];
};

// 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>;
}

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

lib/recipes.ts — getRecipes · getRecipe에 'use cache' · cacheLife('hours') · cacheTag('recipes')와 로그 한 줄(use-cache · cache-args)

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,
    );
  };

app/page.tsx — getPick이 getRecipes() 뒤 await connection()을 기다리고 Math.random()으로 추천을 고름(unstable-values)

app/page.tsx
import {
  Suspense,
} from 'react';
import {
  getRecipes,
} from '@/lib/recipes';
import {
  connection,
} from 'next/server';

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

// 2초 걸리는 읽기라고 칩니다
const getPick = async () => {
  const recipes =
    await getRecipes();
  await connection();
  const at = Math.floor(
    Math.random() *
      recipes.length,
  );
  await wait(2000);
  return recipes[at];
};

// 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>;
}

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

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

Next.js 목차로