Optimistische Aktualisierungen und Cache-Invalidierung
Lassen Sie Mutationen sofort wirken: Verwenden Sie eine optimistische UI und halten Sie anschließend Server- und Client-Zustand mit React-Query-Invalidierung und Next.js-Revalidierungswerkzeugen konsistent.
Optimistische Aktualisierungen und Cache-Invalidierung ist eine kostenlose Next.js 15 Fullstack Web Apps-Lektion auf CoddyKit. Dies ist Lektion 4 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Next.js 15 Fullstack Web Apps-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Next.js 15 Fullstack Web Apps-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
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.
Lerne TypeScript mit einem KI-Tutor — kostenlos
Schreibe und führe echten Code in deinem Browser aus, bekomme sofortige Hilfe von einem 24/7 KI-Tutor und setze dein Lernen im Web oder in der App fort.
- Kurse
- 12
- Lektionen
- 48
Häufig gestellte Fragen
Ist die Lektion „Optimistische Aktualisierungen und Cache-Invalidierung“ kostenlos?
Ja — der vollständige Text von „Optimistische Aktualisierungen und Cache-Invalidierung“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Next.js 15 Fullstack Web Apps-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Next.js 15 Fullstack Web Apps-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „Optimistische Aktualisierungen und Cache-Invalidierung“?
Lassen Sie Mutationen sofort wirken: Verwenden Sie eine optimistische UI und halten Sie anschließend Server- und Client-Zustand mit React-Query-Invalidierung und Next.js-Revalidierungswerkzeugen kons… Du übst Next.js 15 Fullstack Web Apps mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um Next.js 15 Fullstack Web Apps zu starten?
Keine Vorkenntnisse erforderlich. Next.js 15 Fullstack Web Apps auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 4 von 4.
Wie lange dauert die Lektion „Optimistische Aktualisierungen und Cache-Invalidierung“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser Next.js 15 Fullstack Web Apps-Lektion Code schreiben und ausführen?
Ja. Jede Next.js 15 Fullstack Web Apps-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- React Query für Server-State
- Clientseitiger State mit Zustand/Jotai
- Strategien für serverseitiges Caching
- Optimistische Aktualisierungen und Cache-Invalidierung