楽観的更新とキャッシュ無効化
楽観的UIでミューテーションを即時に反映し、React Queryの無効化とNext.jsの再検証機能を使ってサーバーとクライアントの状態を一貫させます。
「楽観的更新とキャッシュ無効化」はCoddyKit上の無料Next.js 15 Fullstack Web Appsレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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.
よくある質問
「楽観的更新とキャッシュ無効化」レッスンは無料ですか?
はい。「楽観的更新とキャッシュ無効化」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Next.js 15 Fullstack Web Appsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Next.js 15 Fullstack Web Appsコースには全4レッスンが含まれています。
「楽観的更新とキャッシュ無効化」で何を学びますか?
楽観的UIでミューテーションを即時に反映し、React Queryの無効化とNext.jsの再検証機能を使ってサーバーとクライアントの状態を一貫させます。 ブラウザで直接実行するハンズオンコードでNext.js 15 Fullstack Web Appsを演習し、24時間対応の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フィードバックを取得できます。ローカル設定は不要です。