0Pricing
Next.js 15 Fullstack Web Apps · Pelajaran

Pembaruan Optimistis dan Invalidasi Cache

Buat mutasi terasa instan dengan UI optimistis, lalu jaga konsistensi state server dan klien menggunakan invalidasi React Query serta alat revalidasi Next.js.

Pembaruan Optimistis dan Invalidasi Cache adalah pelajaran Next.js 15 Fullstack Web Apps gratis di CoddyKit. Ini adalah pelajaran 4 dari 4. Kamu bisa membaca pelajaran lengkapnya di bawah secara gratis — lalu praktikkan langsung di browser dengan editor kode bawaan dan tutor AI 24/7. Ini adalah bagian dari jalur belajar Next.js 15 Fullstack Web Apps, dan progresmu tersinkronisasi di web dan aplikasi CoddyKit. Kursus Next.js 15 Fullstack Web Apps mencakup 4 pelajaran total.

Bagian dari pelajaran ini belum diterjemahkan dan ditampilkan dalam bahasa Inggris.

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 onMutate with a snapshot for rollback.
  • Roll back in onError, reconcile in onSettled.
  • Use revalidatePath and revalidateTag for server cache.
  • Reach for useOptimistic with Server Actions.

Pertanyaan yang Sering Diajukan

Apakah pelajaran “Pembaruan Optimistis dan Invalidasi Cache” gratis?

Ya — teks lengkap “Pembaruan Optimistis dan Invalidasi Cache” gratis dibaca di sini di web. Untuk praktiknya secara interaktif (editor kode bawaan dan tutor AI 24/7) dan buka sisa kursus Next.js 15 Fullstack Web Apps, upgrade ke CoddyKit PRO. Kursus Next.js 15 Fullstack Web Apps mencakup 4 pelajaran total.

Apa yang akan aku pelajari di “Pembaruan Optimistis dan Invalidasi Cache”?

Buat mutasi terasa instan dengan UI optimistis, lalu jaga konsistensi state server dan klien menggunakan invalidasi React Query serta alat revalidasi Next.js. Kamu berlatih Next.js 15 Fullstack Web Apps dengan kode praktik yang langsung kamu jalankan di browser, dan tutor AI 24/7 menjawab pertanyaanmu saat kamu mengerjakan pelajaran ini.

Apakah aku perlu pengalaman untuk memulai Next.js 15 Fullstack Web Apps?

Tidak diperlukan pengalaman sebelumnya. Next.js 15 Fullstack Web Apps di CoddyKit dirancang untuk pemula hingga pelajar tingkat lanjut, jadi kamu bisa memulai di sini atau dari awal dan belajar sesuai kecepatan kamu sendiri. Ini adalah pelajaran 4 dari 4.

Berapa lama pelajaran “Pembaruan Optimistis dan Invalidasi Cache” memakan waktu?

Sebagian besar pelajaran CoddyKit memakan waktu sekitar 5–10 menit. Setiap pelajaran ringkas dan interaktif, jadi kamu membuat kemajuan stabil dan melanjutkan dari tempat kamu tinggalkan di web dan aplikasi.

Bisakah aku menulis dan menjalankan kode dalam pelajaran Next.js 15 Fullstack Web Apps ini?

Ya. Setiap pelajaran Next.js 15 Fullstack Web Apps menyertakan editor kode bawaan, jadi kamu menulis dan menjalankan kode nyata langsung di browser dan mendapatkan umpan balik AI instan — tidak diperlukan penyiapan lokal.

Semua pelajaran dalam kursus ini

  1. React Query untuk State Server
  2. State Sisi Klien dengan Zustand/Jotai
  3. Strategi Caching Sisi Server
  4. Pembaruan Optimistis dan Invalidasi Cache
← Kembali ke Next.js 15 Fullstack Web Apps