낙관적 업데이트와 캐시 무효화
낙관적 UI로 변경 작업이 즉시 처리되는 듯한 경험을 제공한 다음, React Query 무효화와 Next.js 재검증 도구로 서버 상태와 클라이언트 상태를 일관되게 유지합니다.
낙관적 업데이트와 캐시 무효화은(는) CoddyKit의 무료 Next.js 15 Fullstack Web Apps 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Next.js 15 Fullstack Web Apps 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Next.js 15 Fullstack Web Apps 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
What Are Optimistic Updates
An optimistic update applies a mutation to the UI immediately, before the server confirms it. If the request fails, you roll back. This makes apps feel instant.
- Update local cache right away.
- Send the request.
- Reconcile or roll back on the response.
The Tradeoff
Optimism improves perceived speed but risks showing stale or wrong data briefly. Use it for high-confidence actions like likes, toggles, and list edits, not for risky financial operations.
React Query useMutation Basics
useMutation exposes lifecycle hooks: onMutate, onError, onSuccess, and onSettled. Optimistic logic lives in onMutate.
const mutation = useMutation({
mutationFn: updateTodo,
onMutate: async (newTodo) => { /* optimistic */ },
onError: (err, vars, context) => { /* rollback */ },
onSettled: () => { /* refetch */ },
});Snapshot Before Mutating
In onMutate, cancel in-flight queries, snapshot the current cache, then write the optimistic value. The snapshot enables rollback.
onMutate: async (newTodo) => {
await queryClient.cancelQueries({ queryKey: ['todos'] });
const previous = queryClient.getQueryData(['todos']);
queryClient.setQueryData(['todos'], (old) => [...old, newTodo]);
return { previous };
}Rolling Back on Error
If the mutation fails, restore the snapshot you returned from onMutate. The context argument carries it.
onError: (err, newTodo, context) => {
queryClient.setQueryData(['todos'], context.previous);
}Reconciling with the Server
In onSettled, invalidate the query so React Query refetches the authoritative server state, replacing your optimistic guess with real data.
onSettled: () => {
queryClient.invalidateQueries({ queryKey: ['todos'] });
}A Pure Optimistic Reducer
The merge logic is just data transformation. Here is the add-and-rollback idea in plain JS.
let todos = [{ id: 1, text: 'A' }];
const snapshot = [...todos];
todos = [...todos, { id: 2, text: 'B (optimistic)' }];
console.log('optimistic', todos.length);
todos = snapshot;
console.log('rolled back', todos.length);Server-Side: revalidatePath
When a Server Action mutates data, call revalidatePath to purge the Next.js cache for that route so the next render shows fresh data.
'use server';
import { revalidatePath } from 'next/cache';
export async function addTodo(text) {
await db.todo.create({ data: { text } });
revalidatePath('/todos');
}Tag-Based Invalidation
revalidateTag targets cached fetches tagged with a label, regardless of which path used them. Tag your fetches, then invalidate by tag.
await fetch('https://api.example.com/todos', {
next: { tags: ['todos'] },
});
// later, after a mutation:
import { revalidateTag } from 'next/cache';
revalidateTag('todos');useOptimistic in Server Actions
React 19 ships useOptimistic, which pairs naturally with Next.js Server Actions for built-in optimistic UI without a query library.
'use client';
import { useOptimistic } from 'react';
function List({ todos, addAction }) {
const [optimistic, addOptimistic] = useOptimistic(todos);
return <ul>{optimistic.map((t) => <li key={t.id}>{t.text}</li>)}</ul>;
}Choosing the Right Tool
Match the tool to the layer:
invalidateQueries— client cache (React Query).revalidatePath/revalidateTag— server data cache.useOptimistic— instant client feedback with Server Actions.
Quick Check
In a React Query optimistic update, what is the purpose of the value returned from onMutate?
Recap
You learned to keep state consistent during mutations:
- Apply optimistic updates in
onMutatewith a snapshot for rollback. - Roll back in
onError, reconcile inonSettled. - Use
revalidatePathandrevalidateTagfor server cache. - Reach for
useOptimisticwith Server Actions.
AI 튜터와 함께 TypeScript을(를) 배우세요 — 무료
브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.
- 코스
- 12
- 레슨
- 48
자주 묻는 질문
“낙관적 업데이트와 캐시 무효화” 강의는 무료인가요?
네 — “낙관적 업데이트와 캐시 무효화” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Next.js 15 Fullstack Web Apps 강의 전체를 잠금 해제할 수 있습니다. Next.js 15 Fullstack Web Apps 강의에는 총 4개의 강의가 포함되어 있습니다.
“낙관적 업데이트와 캐시 무효화”에서 뭘 배우나요?
낙관적 UI로 변경 작업이 즉시 처리되는 듯한 경험을 제공한 다음, React Query 무효화와 Next.js 재검증 도구로 서버 상태와 클라이언트 상태를 일관되게 유지합니다. 브라우저에서 직접 실행하는 실습 코드로 Next.js 15 Fullstack Web Apps을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Next.js 15 Fullstack Web Apps을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Next.js 15 Fullstack Web Apps은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.
“낙관적 업데이트와 캐시 무효화” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Next.js 15 Fullstack Web Apps 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Next.js 15 Fullstack Web Apps 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 서버 상태를 위한 React Query
- Zustand/Jotai를 사용한 클라이언트 측 상태
- 서버 측 캐싱 전략
- 낙관적 업데이트와 캐시 무효화