Next.js 15 Fullstack Web Apps · บทเรียน

การอัปเดตเชิงมองโลกในแง่ดีและการทำให้แคชเป็นโมฆะ

ทำให้การเปลี่ยนแปลงดูเหมือนเกิดขึ้นทันทีด้วยส่วนติดต่อผู้ใช้เชิงมองโลกในแง่ดี จากนั้นรักษาสถานะฝั่งเซิร์ฟเวอร์และไคลเอนต์ให้สอดคล้องกันด้วยการทำให้แคชของ React Query เป็นโมฆะและเครื่องมือตรวจสอบใหม่ของ Next.js

บทเรียน 4 จาก 413 ขั้นตอน

การอัปเดตเชิงมองโลกในแง่ดีและการทำให้แคชเป็นโมฆะ เป็นบทเรียน Next.js 15 Fullstack Web Apps ฟรีบน CoddyKit นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน 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 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.
เริ่มต้นได้ฟรี

เรียนรู้ TypeScript ด้วย AI tutor — ฟรี

เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป

คอร์ส
12
บทเรียน
48

คำถามที่พบบ่อย

บทเรียน “การอัปเดตเชิงมองโลกในแง่ดีและการทำให้แคชเป็นโมฆะ” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การอัปเดตเชิงมองโลกในแง่ดีและการทำให้แคชเป็นโมฆะ” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Next.js 15 Fullstack Web Apps ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Next.js 15 Fullstack Web Apps มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การอัปเดตเชิงมองโลกในแง่ดีและการทำให้แคชเป็นโมฆะ”

ทำให้การเปลี่ยนแปลงดูเหมือนเกิดขึ้นทันทีด้วยส่วนติดต่อผู้ใช้เชิงมองโลกในแง่ดี จากนั้นรักษาสถานะฝั่งเซิร์ฟเวอร์และไคลเอนต์ให้สอดคล้องกันด้วยการทำให้แคชของ React Query เป็นโมฆะและเครื่องมือตรวจสอบใหม่ข… คุณปฏิบัติ Next.js 15 Fullstack Web Apps ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Next.js 15 Fullstack Web Apps หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Next.js 15 Fullstack Web Apps บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน

บทเรียน “การอัปเดตเชิงมองโลกในแง่ดีและการทำให้แคชเป็นโมฆะ” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Next.js 15 Fullstack Web Apps นี้ได้ไหม

ได้ บทเรียน Next.js 15 Fullstack Web Apps ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. React Query สำหรับสถานะเซิร์ฟเวอร์
  2. สถานะฝั่งไคลเอ็นต์ด้วย Zustand/Jotai
  3. กลยุทธ์การแคชฝั่งเซิร์ฟเวอร์
  4. การอัปเดตเชิงมองโลกในแง่ดีและการทำให้แคชเป็นโมฆะ
← กลับไปที่ Next.js 15 Fullstack Web Apps