İyimser Güncellemeler ve Önbellek Geçersizleştirme
İyimser kullanıcı arayüzüyle değişiklikleri anında gerçekleşiyormuş gibi hissettirin; ardından React Query geçersizleştirmesi ve Next.js yeniden doğrulama araçlarıyla sunucu ve istemci durumunu tutarlı tutun.
İyimser Güncellemeler ve Önbellek Geçersizleştirme, CoddyKit'te ücretsiz bir Next.js 15 Fullstack Web Apps dersidir. Bu, 4 dersinin 4. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, Next.js 15 Fullstack Web Apps öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. Next.js 15 Fullstack Web Apps kursu toplamda 4 dersten oluşur.
Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.
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.
Yapay zeka eğitmeniyle TypeScript öğren — ücretsiz
Tarayıcında gerçek kod yaz ve çalıştır, 7/24 yapay zeka eğitmeninden anında yardım al; web'de ya da uygulamada kaldığın yerden devam et.
- Kurslar
- 12
- Dersler
- 48
Sıkça Sorulan Sorular
“İyimser Güncellemeler ve Önbellek Geçersizleştirme” dersi ücretsiz mi?
Evet — “İyimser Güncellemeler ve Önbellek Geçersizleştirme” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve Next.js 15 Fullstack Web Apps kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. Next.js 15 Fullstack Web Apps kursu toplamda 4 dersten oluşur.
“İyimser Güncellemeler ve Önbellek Geçersizleştirme” dersinde ne öğreneceğim?
İyimser kullanıcı arayüzüyle değişiklikleri anında gerçekleşiyormuş gibi hissettirin; ardından React Query geçersizleştirmesi ve Next.js yeniden doğrulama araçlarıyla sunucu ve istemci durumunu tutar… Next.js 15 Fullstack Web Apps ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.
Next.js 15 Fullstack Web Apps öğrenmeye başlamak için deneyim gerekli mi?
Önceden deneyim gerekmez. CoddyKit'te Next.js 15 Fullstack Web Apps, başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 4 dersinin 4. dersidir.
“İyimser Güncellemeler ve Önbellek Geçersizleştirme” dersi ne kadar sürer?
Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.
Bu Next.js 15 Fullstack Web Apps dersinde kod yazıp çalıştırabilir miyim?
Evet. Her Next.js 15 Fullstack Web Apps dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.
Bu kursun tüm dersleri
- Sunucu Durumu için React Query
- Zustand/Jotai ile İstemci Tarafı Durumu
- Sunucu Tarafı Önbelleğe Alma Stratejileri
- İyimser Güncellemeler ve Önbellek Geçersizleştirme