0Pricing
Next.js 15 Fullstack Web Apps · Aula

Atualizações otimistas e invalidação de cache

Faça as mutações parecerem instantâneas com uma interface otimista e mantenha o estado do servidor e do cliente consistente usando a invalidação do React Query e as ferramentas de revalidação do Next.js.

Atualizações otimistas e invalidação de cache é uma aula grátis de Next.js 15 Fullstack Web Apps no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Next.js 15 Fullstack Web Apps, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Next.js 15 Fullstack Web Apps inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

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.

Perguntas Frequentes

A aula “Atualizações otimistas e invalidação de cache” é grátis?

Sim — o texto completo de “Atualizações otimistas e invalidação de cache” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Next.js 15 Fullstack Web Apps, atualize para CoddyKit PRO. O curso de Next.js 15 Fullstack Web Apps inclui 4 aulas no total.

O que vou aprender em “Atualizações otimistas e invalidação de cache”?

Faça as mutações parecerem instantâneas com uma interface otimista e mantenha o estado do servidor e do cliente consistente usando a invalidação do React Query e as ferramentas de revalidação do Next… Você pratica Next.js 15 Fullstack Web Apps com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Next.js 15 Fullstack Web Apps?

Nenhuma experiência prévia é necessária. Next.js 15 Fullstack Web Apps no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.

Quanto tempo leva a aula “Atualizações otimistas e invalidação de cache”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Next.js 15 Fullstack Web Apps?

Sim. Cada aula de Next.js 15 Fullstack Web Apps inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. React Query para Estado do Servidor
  2. Estado no Cliente com Zustand/Jotai
  3. Estratégias de Cache no Servidor
  4. Atualizações otimistas e invalidação de cache
← Voltar para Next.js 15 Fullstack Web Apps