updateTag는 서버 함수 안에서 부르는 함수로, 같은 이름이 붙은 기억을 바로 지워 다음 요청이 데이터를 새로 읽게 합니다. 이 레슨은 createRecipe 끝에 updateTag('recipes') 한 줄을 더해, 더한 레시피가 목록에 바로 보이는 차례를 서버 터미널로 봅니다.
서버 함수 끝 장면을 다시 엽니다. 코드를 고쳐 저장 → 목록을 한 번 연다 → /recipes/new에서 크림 파스타를 더한다 → 다시 연다. 파일에는 크림 파스타가 있는데 목록은 넷 그대로였습니다. getRecipes는 cacheTag('recipes')로 이름이 붙은 채 처음 읽은 넷을 기억했고, createRecipe는 파일에만 썼기 때문입니다. 기억을 지우는 일도 서버 함수가 해야 합니다.
1서버 함수 안에서 updateTag 부르기
app/actions.ts 맨 위에서 next/cache의 updateTag를 가져오고, 저장한 다음 줄에서 부릅니다.
'use server';
import {
updateTag,
} from 'next/cache';
…
// 3. 저장하기
await addRecipe({
…
});
// 4. 기억 지우기
updateTag('recipes');
}
…'recipes'는 use cache에서getRecipes에, 인자가 열쇠다에서getRecipe에 단cacheTag('recipes')의 이름입니다. 이 이름이 붙은 기억이 모두 지워집니다.- 목록 · 통계 · 레시피 쪽은 모두 이 두 함수로 읽습니다. 그래서 세 쪽 모두 다음 요청에 새 목록을 봅니다. 지운 뒤 처음 연 쪽이 파일을 새로 읽고, 다른 쪽은 그때 다시 채운 기억을 씁니다.
updateTag는 서버 함수 안에서만 부릅니다(Next.js 문서 updateTag — 'can only be called from within Server Actions'). 쪽 함수 안에서 부르면 빌드가can't be called during render오류로 멈춥니다.
저장할 때 레시피 보관함 탭은 닫아 둡니다. 저장했으면 같은 차례로 합니다.
- 새 탭의 주소 칸에
/recipes를 쳐서 목록을 한 번 엽니다. - 같은 탭 주소 칸에
/recipes/new를 쳐서 이름크림 파스타, 분류양식, 분20을 넣고 '더하기'를 누릅니다. - 같은 탭 주소 칸에
/recipes를 쳐서 새로 엽니다. - 같은 탭 주소 칸에
/stats를 쳐서 통계 쪽도 엽니다.
app/actions.ts 전체 · 목록 · 통계 화면 · 서버 터미널
아래는 고친 app/actions.ts, 3에서 연 목록 화면, 4에서 연 통계 화면, 4까지 마친 서버 터미널입니다. 시간과 레시피 주소의 긴 글자는 다를 수 있습니다.
'use server';
import {
updateTag,
} from 'next/cache';
import {
addRecipe,
} from '@/lib/recipes';
async function createRecipe(
formData: FormData,
) {
const title =
formData.get('title');
const category =
formData.get('category');
if (
typeof title !== 'string' ||
typeof category !== 'string'
) {
return;
}
// 3. 저장하기
await addRecipe({
title,
category,
minutes: Number(
formData.get('minutes'),
),
});
// 4. 기억 지우기
updateTag('recipes');
}
export { createRecipe };<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/6a4b7ac9-83ee-4d6b-886a-8206faec99ea">크림 파스타</a><button>☆</button></li></ul></section><footer>바닥글</footer><nav><a href="/recipes">목록</a>·<a href="/stats">▸ 통계</a></nav><h1>통계</h1><p>모두 5개</p><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 325ms
✓ Running next.config.ts took 1226ms
- Cache Components enabled
- Partial Prefetching enabled
레시피 파일 읽음
Cache 레시피 파일 읽음
GET /recipes 200 in 201ms (next.js: 66ms, application-code: 135ms)
Cache 레시피 파일 읽음
Cache 레시피 파일 읽음
GET /recipes/new 200 in 33ms (next.js: 12ms, application-code: 21ms)
POST /recipes/new 200 in 20ms (next.js: 1.1ms, application-code: 18ms)
└─ ƒ createRecipe({}) in 1ms app/actions.ts
레시피 파일 읽음
Cache 레시피 파일 읽음
GET /recipes 200 in 46ms (next.js: 0.8ms, application-code: 45ms)
Cache 레시피 파일 읽음
Cache 레시피 파일 읽음
Cache 레시피 파일 읽음
GET /stats 200 in 20ms (next.js: 3ms, application-code: 17ms)
목록에 크림 파스타가 보이고, 통계도 모두 5개입니다. 서버 터미널에서 POST /recipes/new 뒤 첫 레시피 파일 읽음에는 Cache 꼬리표가 없습니다. updateTag가 기억을 지워, 3의 요청이 파일을 새로 읽은 줄입니다. 4의 통계 쪽은 그때 새로 채운 기억을 썼습니다(Cache가 붙은 줄).
2POST의 응답에 실려 오는 것
'더하기'를 누른 POST에 서버는 무엇을 돌려줄까요? 서버가 쪽을 그리는지 보려고, 폼이 있는 /recipes/new의 쪽 함수 맨 앞에 로그 한 줄을 둡니다.
…
function Page() {
console.log(
'더하기 쪽을 그림',
);
…탭을 닫은 채 저장했으면, 새 탭의 주소 칸에 /recipes를 쳐서 목록을 한 번 엽니다. 이어 같은 탭에서 /recipes/new를 열고 떡볶이(분 30)를 더합니다. 폼을 열 때 더하기 쪽을 그림이 한 번 찍힙니다. '더하기'를 누른 뒤에는 어떨까요? 고른 뒤 펼쳐 보세요. 맞혀 보기는 점수에 들지 않습니다.
- ① 또 찍힌다 — POST 안에서 쪽을 다시 그렸다
- ② 찍히지 않는다 — 서버 함수만 돌았다
- ③ 찍히고,
GET /recipes/new줄이 하나 더 생긴다 — 브라우저가 쪽을 새로 받았다
결과 보기
①입니다. 아래는 1절 그대로의 app/actions.ts, 로그를 더한 쪽 파일, 떡볶이를 더하기까지 마친 서버 터미널입니다.
'use server';
import {
updateTag,
} from 'next/cache';
import {
addRecipe,
} from '@/lib/recipes';
async function createRecipe(
formData: FormData,
) {
const title =
formData.get('title');
const category =
formData.get('category');
if (
typeof title !== 'string' ||
typeof category !== 'string'
) {
return;
}
// 3. 저장하기
await addRecipe({
title,
category,
minutes: Number(
formData.get('minutes'),
),
});
// 4. 기억 지우기
updateTag('recipes');
}
export { createRecipe };import {
createRecipe,
} from '@/app/actions';
import {
categories,
} from '@/lib/recipes';
// 1. 폼에 서버 함수 달기
function Page() {
console.log(
'더하기 쪽을 그림',
);
const options =
categories.map((c) => (
<option key={c}>
{c}
</option>
));
return (
<form action={createRecipe}>
<input
name="title"
placeholder="이름"
/>
<select
name="category"
aria-label="분류"
>
{options}
</select>
<input
name="minutes"
type="number"
placeholder="분"
/>
<button>더하기</button>
</form>
);
}
export default Page;> 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 225ms
✓ Running next.config.ts took 1057ms
- Cache Components enabled
- Partial Prefetching enabled
레시피 파일 읽음
Cache 레시피 파일 읽음
GET /recipes 200 in 175ms (next.js: 63ms, application-code: 112ms)
Cache 레시피 파일 읽음
Cache 레시피 파일 읽음
더하기 쪽을 그림
GET /recipes/new 200 in 30ms (next.js: 11ms, application-code: 20ms)
더하기 쪽을 그림
POST /recipes/new 200 in 17ms (next.js: 0.8ms, application-code: 16ms)
└─ ƒ createRecipe({}) in 1ms app/actions.ts
폼을 열 때 한 번, '더하기'를 누른 POST 안에서 한 번 더 찍혔습니다. 둘째 줄이 POST /recipes/new 200보다 위에 있는 것은, 요청 줄이 응답을 다 보낸 뒤에 찍히기 때문입니다. 서버는 createRecipe를 마치고 /recipes/new를 다시 그려, 돌려준 값과 함께 같은 응답에 실었습니다(Next.js 문서 Server Actions 'A single response carries data and UI'). GET /recipes/new 줄은 더 생기지 않았습니다. 브라우저가 쪽을 새로 받으러 가지 않았다는 뜻입니다.
이 응답은 개발 판에서 JS로 보낸 폼이 updateTag를 부른 때 잰 것입니다. updateTag 같은 부름이 없을 때는 어떨지 해 보기에서 봅니다. JS를 끈 폼은 updateTag가 있든 없든 같은 쪽의 HTML을 새로 받습니다(서버 함수 해 보기).
3기억을 지우는 다른 이름
next/cache에는 기억을 지우는 함수가 둘 더 있습니다. 이 과목은 updateTag만 씁니다.
revalidatePath('/recipes')— 이름 대신 주소로 지웁니다. 다음 요청에 새로 그리는 것은 그 주소의 쪽입니다. 배포 판에서 빌드 때 미리 그려 둔 다른 쪽(○)은 같은 데이터를 써도 그려 둔 옛 쪽을 그대로 줍니다(Next.js 문서 revalidatePath).revalidateTag— 둘째 인자를'max'로 주면 바로 지우지 않습니다. 다음 요청에는 옛 목록을 주고 뒤에서 새로 읽습니다(Next.js 문서 revalidateTag). 더한 사람이 바로 봐야 하는 폼에는updateTag가 맞습니다.
해 보기 — updateTag 줄을 지우고 더하기
먼저 data/recipes.json에서 1 · 2절에 더한 크림 파스타 · 떡볶이를 지워 씨앗 넷으로 되돌립니다. 그다음 app/actions.ts에서 updateTag('recipes'); 줄과 맨 위 updateTag import를 지우고 탭을 닫은 채 저장합니다. 새 탭으로 목록을 한 번 연 뒤 같은 탭에서 /recipes/new를 열어 계란국(분 15)을 더하고, /recipes를 다시 엽니다. 목록과 터미널은 어떨까요? 고른 뒤 펼쳐 보세요.
- ① 목록에 보이고, '더하기'를 누를 때
더하기 쪽을 그림도 찍힌다 - ② 목록은 그대로고, '더하기'를 누를 때
더하기 쪽을 그림이 찍히지 않는다 - ③ 목록은 그대로고, '더하기'를 누를 때
더하기 쪽을 그림은 찍힌다
결과 보기
②입니다. 아래는 두 줄을 지운 app/actions.ts, 2절 그대로의 쪽 파일, 다시 연 목록 화면과 서버 터미널입니다.
'use server';
import {
addRecipe,
} from '@/lib/recipes';
async function createRecipe(
formData: FormData,
) {
const title =
formData.get('title');
const category =
formData.get('category');
if (
typeof title !== 'string' ||
typeof category !== 'string'
) {
return;
}
// 3. 저장하기
await addRecipe({
title,
category,
minutes: Number(
formData.get('minutes'),
),
});
}
export { createRecipe };import {
createRecipe,
} from '@/app/actions';
import {
categories,
} from '@/lib/recipes';
// 1. 폼에 서버 함수 달기
function Page() {
console.log(
'더하기 쪽을 그림',
);
const options =
categories.map((c) => (
<option key={c}>
{c}
</option>
));
return (
<form action={createRecipe}>
<input
name="title"
placeholder="이름"
/>
<select
name="category"
aria-label="분류"
>
{options}
</select>
<input
name="minutes"
type="number"
placeholder="분"
/>
<button>더하기</button>
</form>
);
}
export default Page;<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 216ms
✓ Running next.config.ts took 1000ms
- Cache Components enabled
- Partial Prefetching enabled
레시피 파일 읽음
Cache 레시피 파일 읽음
GET /recipes 200 in 166ms (next.js: 62ms, application-code: 104ms)
Cache 레시피 파일 읽음
Cache 레시피 파일 읽음
더하기 쪽을 그림
GET /recipes/new 200 in 33ms (next.js: 11ms, application-code: 22ms)
POST /recipes/new 200 in 9ms (next.js: 0.8ms, application-code: 8ms)
└─ ƒ createRecipe({}) in 2ms app/actions.ts
Cache 레시피 파일 읽음
GET /recipes 200 in 42ms (next.js: 1.1ms, application-code: 41ms)
목록은 씨앗 넷 그대로입니다. 터미널에서 폼을 열 때 찍힌 더하기 쪽을 그림 뒤로는 그 줄이 없습니다. 지우는 부름이 없으니, 서버는 쪽을 다시 그리지 않고 돌려준 값만 보냈습니다. 다시 연 목록은 Cache가 붙은 줄 하나 — 기억한 넷을 썼습니다.
다 봤으면 지운 두 줄을 되살려 1절의 app/actions.ts로 되돌리고 저장합니다.
예제
같은 일을 배포 판에서 셉니다. 개발 서버를 Ctrl+C로 끄고 npm run build → npm run start로 띄웁니다. 탭 하나로, 주소 칸에 /recipes를 쳐서 목록을 한 번 열고, /recipes/new에서 김밥(분 10)을 더합니다. 그다음 주소 칸에 /stats를 쳐서 통계 쪽을 두 번 엽니다. 통계 쪽도 같은 getRecipes()로 읽습니다. 김밥을 더한 뒤 서버 터미널에 레시피 파일 읽음은 몇 번 찍힐까요? 고른 뒤 펼쳐 보세요. 맞혀 보기는 점수에 들지 않습니다.
- ① 0번 — 배포 판은 빌드 때 읽은 목록을 쓰니까
- ② 두 번 — 쪽을 열 때마다 새로 읽으니까
- ③ 한 번 — 지운 뒤 첫 요청만 새로 읽는다
결과 보기
③입니다. 아래는 1절 그대로의 app/actions.ts, 2절 그대로의 쪽 파일, 배포 서버의 터미널입니다.
'use server';
import {
updateTag,
} from 'next/cache';
import {
addRecipe,
} from '@/lib/recipes';
async function createRecipe(
formData: FormData,
) {
const title =
formData.get('title');
const category =
formData.get('category');
if (
typeof title !== 'string' ||
typeof category !== 'string'
) {
return;
}
// 3. 저장하기
await addRecipe({
title,
category,
minutes: Number(
formData.get('minutes'),
),
});
// 4. 기억 지우기
updateTag('recipes');
}
export { createRecipe };import {
createRecipe,
} from '@/app/actions';
import {
categories,
} from '@/lib/recipes';
// 1. 폼에 서버 함수 달기
function Page() {
console.log(
'더하기 쪽을 그림',
);
const options =
categories.map((c) => (
<option key={c}>
{c}
</option>
));
return (
<form action={createRecipe}>
<input
name="title"
placeholder="이름"
/>
<select
name="category"
aria-label="분류"
>
{options}
</select>
<input
name="minutes"
type="number"
placeholder="분"
/>
<button>더하기</button>
</form>
);
}
export default Page;> 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 72ms
✓ Running next.config.ts took 17ms
레시피 파일 읽음
더하기 쪽을 그림
레시피 파일 읽음
배포 판 터미널에는 요청 줄이 없고 로그만 찍힙니다. 첫 레시피 파일 읽음은 처음 연 목록입니다. 더하기 쪽을 그림은 김밥을 더한 POST가 쪽을 다시 그린 줄입니다(폼을 연 요청은 빌드 때 그려 둔 쪽을 받아 찍지 않습니다). 그다음 레시피 파일 읽음 하나가 지운 뒤 첫 통계 요청이고, 둘째 요청은 그 기억을 써서 찍지 않았습니다.
다 봤으면 배포 판을 Ctrl+C로 끄고, data/recipes.json에서 더한 레시피(계란국 · 김밥)를 지워 씨앗 넷으로 되돌린 뒤 npm run dev로 개발 서버를 다시 띄웁니다. 다음 레슨도 씨앗 넷에서 시작합니다.
자주 틀리는 곳
틀린 생각: 파일에 저장했으니 다음 요청에는 새 목록이 보인다.
맞는 규칙: 'use cache'를 단 함수는 기억한 결과를 줍니다(Next.js 규칙 7). 저장한 서버 함수 안에서 updateTag로 그 이름의 기억을 지워야 다음 요청이 새로 읽습니다.
틀린 생각: updateTag는 어디서 불러도 된다.
맞는 규칙: 서버 함수 안에서만 부릅니다. 쪽 함수 안에서 부르면 can't be called during render 오류로 멈춥니다.
틀린 생각: 이름 글자가 조금 달라도 비슷한 기억이 지워진다.
맞는 규칙: updateTag('recipe')처럼 cacheTag('recipes')와 한 글자만 달라도 지워지는 기억이 없습니다. 오류도 나지 않으니, 목록이 그대로면 두 이름부터 맞춰 봅니다.
확인 문제
문제 1. createRecipe 안에서 updateTag('recipes')를 부르는 까닭은 무엇일까요?
- ①
data/recipes.json에 저장하려고 - ② 폼 칸을 비우려고
- ③
cacheTag('recipes')를 단 기억을 지워 다음 요청이 새로 읽게 하려고
정답
③입니다. 지우지 않으면 getRecipes는 기억한 옛 목록을 줍니다.
- ① 저장은
addRecipe가 합니다.updateTag는 파일을 건드리지 않습니다. - ② 칸을 비우는 일과는 상관이 없습니다.
문제 2. (개발 판 · JS로 보낸 폼) createRecipe가 updateTag를 부르면, '더하기'를 누른 POST의 응답에는 무엇이 함께 올까요?
- ① 다시 그린 지금 쪽(
/recipes/new) - ②
data/recipes.json파일 전체 - ③
createRecipe함수의 코드
정답
①입니다. 서버가 POST 안에서 지금 쪽을 다시 그려 같은 응답에 싣습니다. 그래서 '더하기'를 누를 때 더하기 쪽을 그림이 또 찍혔습니다.
- ② 파일은 서버에 남습니다. 브라우저는 그린 결과만 받습니다.
- ③ 함수 몸은 서버에 남습니다(서버 함수).
문제 3. 더하기 전에 /stats를 한 번 열어 두었습니다. updateTag('recipes')로 지운 뒤 /stats를 다시 열면 통계 쪽의 레시피 수는 어떨까요?
- ① 더하기 전 수 — 통계 쪽은 지우지 않았으니까
- ② 더한 뒤 수 — 같은
getRecipes의 기억이 지워져 새로 읽으니까 - ③ 쪽이 오류로 멈춘다
정답
②입니다. 지운 것은 쪽이 아니라 recipes 이름이 붙은 getRecipes의 기억입니다. 그 함수를 쓰는 쪽은 모두 다음 요청에 새로 읽습니다.
- ① 이름은 쪽마다 따로가 아니라 함수의 기억에 붙어 있습니다.
- ③ 기억이 없으면 함수를 다시 돌릴 뿐입니다.
이 레슨에서 바꾼 파일
app/actions.ts — updateTag import · 저장 뒤 updateTag('recipes')
'use server';
import {
updateTag,
} from 'next/cache';
import {
addRecipe,
} from '@/lib/recipes';
async function createRecipe(
formData: FormData,
) {
const title =
formData.get('title');
const category =
formData.get('category');
if (
typeof title !== 'string' ||
typeof category !== 'string'
) {
return;
}
// 3. 저장하기
await addRecipe({
title,
category,
minutes: Number(
formData.get('minutes'),
),
});
// 4. 기억 지우기
updateTag('recipes');
}
export { createRecipe };app/recipes/new/page.tsx — 쪽 함수 맨 앞에 로그 한 줄
import {
createRecipe,
} from '@/app/actions';
import {
categories,
} from '@/lib/recipes';
// 1. 폼에 서버 함수 달기
function Page() {
console.log(
'더하기 쪽을 그림',
);
const options =
categories.map((c) => (
<option key={c}>
{c}
</option>
));
return (
<form action={createRecipe}>
<input
name="title"
placeholder="이름"
/>
<select
name="category"
aria-label="분류"
>
{options}
</select>
<input
name="minutes"
type="number"
placeholder="분"
/>
<button>더하기</button>
</form>
);
}
export default Page;