0Pricing
Next.js 15 Fullstack Web Apps · Lezione

Aggiornamenti ottimistici e invalidazione della cache

Renda istantanee le mutation con una UI ottimistica, quindi mantenga coerenti lo stato del server e quello del client usando l’invalidazione di React Query e gli strumenti di revalidation di Next.js.

Aggiornamenti ottimistici e invalidazione della cache è una lezione Next.js 15 Fullstack Web Apps gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Next.js 15 Fullstack Web Apps, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Next.js 15 Fullstack Web Apps include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

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.

Domande Frequenti

La lezione «Aggiornamenti ottimistici e invalidazione della cache» è gratuita?

Sì — il testo completo di «Aggiornamenti ottimistici e invalidazione della cache» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Next.js 15 Fullstack Web Apps, passa a CoddyKit PRO. Il corso Next.js 15 Fullstack Web Apps include 4 lezioni in totale.

Cosa imparerò in «Aggiornamenti ottimistici e invalidazione della cache»?

Renda istantanee le mutation con una UI ottimistica, quindi mantenga coerenti lo stato del server e quello del client usando l’invalidazione di React Query e gli strumenti di revalidation di Next.js. Eserciti Next.js 15 Fullstack Web Apps con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Next.js 15 Fullstack Web Apps?

Non è richiesta alcuna esperienza precedente. Next.js 15 Fullstack Web Apps su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.

Quanto tempo richiede la lezione «Aggiornamenti ottimistici e invalidazione della cache»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Next.js 15 Fullstack Web Apps?

Sì. Ogni lezione Next.js 15 Fullstack Web Apps include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. React Query per lo stato del server
  2. Stato lato client con Zustand/Jotai
  3. Strategie di caching lato server
  4. Aggiornamenti ottimistici e invalidazione della cache
← Torna a Next.js 15 Fullstack Web Apps