데이터 변경 및 재검증
Server Actions가 서버의 데이터를 변경하고 UI를 업데이트하기 위해 캐시된 데이터를 자동으로 재검증하는 방법을 배웁니다.
데이터 변경 및 재검증은(는) CoddyKit의 무료 Next.js 15 Fullstack (App Router + Server Actions) 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Next.js 15 Fullstack (App Router + Server Actions) 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Next.js 15 Fullstack (App Router + Server Actions) 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
What is Data Mutation?
In web development, data mutation means changing data on the server. This includes creating new data, updating existing records, or deleting data.
- Create: Adding a new user.
- Update: Changing a user's email.
- Delete: Removing an item from a list.
Most interactive web applications rely heavily on data mutation to provide dynamic experiences.
Server Actions for Mutations
Next.js 15's Server Actions are perfect for handling data mutations. They allow you to run server-side code directly from your React components, making it simple to update your backend.
Instead of creating API routes for every data change, you can define these actions right where they're needed, keeping your code organized and efficient.
The Cache Challenge
When you mutate data on the server, the client-side UI often doesn't automatically reflect these changes. This is because Next.js (and browsers) aggressively cache data to improve performance.
If the UI still shows old, cached data after a server update, users see outdated information. We need a way to tell Next.js: "Hey, this data has changed, please get the fresh version!"
Revalidating with `revalidatePath`
To ensure your UI shows the latest data, Next.js provides caching utilities. One common method is revalidatePath.
After a Server Action changes data, you can call revalidatePath('/') to tell Next.js to invalidate the cache for the specified path (e.g., the home page) and refetch its data on the next request.
Demo: Update & Revalidate Path
This example shows a simple form that adds a task using a Server Action. After the task is added, revalidatePath('/') ensures that any data displayed on the root page (like a list of tasks) is refreshed.
import { revalidatePath } from 'next/cache';
async function addTask(formData) {
'use server';
const task = formData.get('task');
// Simulate saving to a database
console.log('Adding task:', task);
await new Promise(r => setTimeout(r, 500));
// Revalidate the home page to show new tasks
revalidatePath('/');
}
export default function Page() {
return (
<div>
<h1>My Task List</h1>
<form action={addTask}>
<input type="text" name="task" placeholder="New task" required />
<button type="submit">Add Task</button>
</form>
<p>Task list will refresh after adding!</p>
</div>
);
}Granular Control with `revalidateTag`
Sometimes you need more granular control over caching than just revalidating an entire path. This is where revalidateTag comes in.
When fetching data, you can assign a custom tag using the fetch API. Then, after a mutation, you can use revalidateTag('my-data-tag') to invalidate only the data associated with that specific tag.
When to use `revalidateTag`
Use revalidateTag when:
- Data is fetched from an external API using
fetch. - The data is shared across multiple pages or components.
- You want to update specific data without re-rendering entire pages.
It's ideal for scenarios like updating a single user's profile data that might appear on various pages.
Post-Mutation Redirection
After a successful data mutation, you often want to redirect the user to another page (e.g., a success page or the updated list page). Next.js provides a redirect helper for this.
You can use redirect('/dashboard') inside your Server Action to send the user to the dashboard after a form submission.
Full Flow: Mutate, Revalidate, Redirect
This example combines all concepts: a form submission triggers a Server Action, which mutates data, revalidates the relevant path, and then redirects the user to a confirmation page.
import { revalidatePath, redirect } from 'next/cache';
async function createPost(formData) {
'use server';
const title = formData.get('title');
const content = formData.get('content');
// Simulate saving new post to a DB
console.log('New Post:', { title, content });
await new Promise(r => setTimeout(r, 700));
revalidatePath('/posts'); // Revalidate the posts list page
redirect('/posts/success'); // Redirect to a success page
}
export default function NewPostPage() {
return (
<div>
<h1>Create New Post</h1>
<form action={createPost}>
<input type="text" name="title" placeholder="Title" required />
<textarea name="content" placeholder="Content" required />
<button type="submit">Publish Post</button>
</form>
</div>
);
}Quick Check on Revalidation
A Server Action successfully creates a new product and you want to update the product listing page (/products) and also ensure any cached data specifically tagged 'featured-products' is refreshed. Which revalidation methods should you use?
Recap: Mutate & Revalidate
Great job! You've learned how Server Actions are key to mutating data on the server. You also mastered how to keep your UI fresh:
- Use Server Actions for creating, updating, or deleting data.
- Employ
revalidatePathto refresh data for specific routes. - Utilize
revalidateTagfor fine-grained cache invalidation of taggedfetchrequests. - Use
redirectto guide users after a successful action.
This powerful combination ensures your Next.js applications are always showing accurate, up-to-date information.
자주 묻는 질문
“데이터 변경 및 재검증” 강의는 무료인가요?
네 — “데이터 변경 및 재검증” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Next.js 15 Fullstack (App Router + Server Actions) 강의 전체를 잠금 해제할 수 있습니다. Next.js 15 Fullstack (App Router + Server Actions) 강의에는 총 4개의 강의가 포함되어 있습니다.
“데이터 변경 및 재검증”에서 뭘 배우나요?
Server Actions가 서버의 데이터를 변경하고 UI를 업데이트하기 위해 캐시된 데이터를 자동으로 재검증하는 방법을 배웁니다. 브라우저에서 직접 실행하는 실습 코드로 Next.js 15 Fullstack (App Router + Server Actions)을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Next.js 15 Fullstack (App Router + Server Actions)을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Next.js 15 Fullstack (App Router + Server Actions)은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“데이터 변경 및 재검증” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Next.js 15 Fullstack (App Router + Server Actions) 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Next.js 15 Fullstack (App Router + Server Actions) 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.