Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 72 ยท Mutations and Forms

Optimistic UI and Refreshing After Mutations

Make mutations feel instant with useOptimistic, then show real data with revalidatePath, redirect and router.refresh. Includes live rollback demos.

When a visitor clicks a "like" button, the honest sequence of events is: send the request, wait for the server, update the screen. On a fast network that is a blink. On a slow one, the button seems dead for a second, and people click again. An optimistic update flips the order. You assume the request will succeed, update the screen immediately, and let the real result arrive afterwards. If it fails, the screen goes back to the truth.

A Server Action that changes data raises a second question: how does the page learn that its data is now stale? This lesson covers both halves. First the useOptimistic hook for instant feedback, then the tools Next.js gives you to show real data afterwards: revalidatePath, redirect and router.refresh().

Real or stand-in? useOptimistic is a plain React 19 hook, so the two live examples use the real hook. The "server" in them is a function with a delay in the same page. revalidatePath, redirect and router.refresh() need a Next.js server, so those appear as real read-only code.

The idea in four steps

Optimistic updates, step by step

User acts A click or a form submit.
Show it now Add a temporary, optimistic copy to the screen.
Server works The real request runs in the background.
Real data wins The optimistic copy is replaced by the truth.

If the request fails, the temporary copy just disappears.

1 / 2
sequenceDiagram
    participant U as User
    participant UI as Screen
    participant S as Server
    U->>UI: Click "Add"
    UI->>UI: Show optimistic item at once
    UI->>S: Send the real request
    S-->>UI: Real data (or an error)
    UI->>UI: Replace optimistic item with the truth

The screen answers first; the server's answer arrives later and takes over.

useOptimistic

useOptimistic takes a piece of real state and a function that says how to apply a temporary change on top of it:

TSX
const [optimisticValue, addOptimistic] = useOptimistic(realValue, (current, change) => nextValue);

You render optimisticValue. While a transition (a form action counts) is running, optimisticValue is the real value with your changes applied. When the transition ends, React throws the optimistic layer away and shows the real value again. That is the whole trick: the optimistic state is temporary by design, so a failed request needs no cleanup code. The real state never changed, so the screen falls back by itself.

Here it is inside a form in a Next.js Client Component. The messages prop comes from a Server Component that read the database, and sendMessage is a Server Action.

TSX
'use client';

import { useOptimistic } from 'react';
import { sendMessage } from '@/app/actions';

type Message = { id: string; text: string; sending?: boolean };

export function Chat({ messages }: { messages: Message[] }) {
  const [shown, addOptimistic] = useOptimistic(
    messages,
    (current: Message[], text: string) => [...current, { id: 'temp-' + text, text, sending: true }],
  );

  async function action(formData: FormData) {
    const text = String(formData.get('text') ?? '');
    addOptimistic(text);          // instant
    await sendMessage(text);      // real work; revalidates the page
  }

  return (
    <>
      <ul>
        {shown.map((m) => (
          <li key={m.id} style={{ opacity: m.sending ? 0.5 : 1 }}>{m.text}</li>
        ))}
      </ul>
      <form action={action}>
        <input name="text" />
        <button>Send</button>
      </form>
    </>
  );
}

Call addOptimistic before the await, and only inside an action or a transition. After the action finishes and the server revalidates the page, new messages arrive as props and replace the temporary layer.

This stand-in uses the real hook with a fake server that takes 800 ms. Add some items and watch each one appear at once, grey and marked "saving...", then turn solid.

Optimistic todo list with useOptimistic

Watch the last line: "Server has N items" only changes after the delay, while the list changed instantly. That gap is the whole benefit.

Rolling back when it fails

Optimism must be backed by an honest failure path. Because useOptimistic discards its layer when the transition ends, the rollback is automatic. You only need to tell the user what happened. In this like button, tick Go offline and click: the heart fills in at once, then snaps back and a message explains why.

A like button that rolls back on failure

With the checkbox off, the heart fills and "saved: liked" confirms it. With it on, the heart fills for 700 ms, then returns to empty while the message appears. The real liked state was never changed, so there was nothing to undo.

Never use optimism for actions where a wrong guess is costly, such as payments, bookings that can sell out, or anything the user cannot easily see reversed. Show a pending state and wait for the server instead.

Refreshing server data after a mutation

Optimism only decorates the gap. The page also needs the real data once the action is done. Next.js gives you several tools, and they all do the same job: tell the framework that something it showed is now out of date.

revalidatePath marks everything cached for a URL as stale. Call it in the action after you change the data:

TypeScript
'use server';

import { revalidatePath } from 'next/cache';

export async function sendMessage(text: string) {
  await db.message.create({ data: { text } });
  revalidatePath('/chat');
}

When an action calls revalidatePath, Next.js re-renders the affected page and returns the fresh UI in the same response as the action result. That is why in the chat example the new messages prop arrives without any extra fetch. If the page's data is tagged instead of identified by URL, use revalidateTag (and in Next.js 16, updateTag inside a Server Action when you need the user to see their own change immediately). Those are the subject of Revalidating Data.

redirect sends the user to another page, which suits "create something, then show it":

TypeScript
'use server';

import { redirect } from 'next/navigation';
import { revalidatePath } from 'next/cache';

export async function createPost(formData: FormData) {
  const post = await db.post.create({ data: { title: String(formData.get('title')) } });
  revalidatePath('/posts');
  redirect('/posts/' + post.id);
}

Two rules about redirect. It works by throwing a special error that Next.js catches, so never call it inside a try/catch that swallows errors, or the redirect is lost. And run revalidatePath before it, because code after redirect never executes.

router.refresh() is for Client Components that are not inside an action. It asks the server for a fresh render of the current route and merges it in, while keeping client state such as typed text and open dialogs:

TSX
'use client';

import { useRouter } from 'next/navigation';

export function RefreshButton() {
  const router = useRouter();
  return <button onClick={() => router.refresh()}>Refresh</button>;
}

Prefer revalidatePath or revalidateTag inside the action, because they also fix what is cached on the server. router.refresh() is the tool for polling-style updates or after a change made by something other than an action, such as a call to a Route Handler.

Putting it together

A solid mutation flow in the App Router looks like this:

  1. The form (or button) calls a Server Action.
  2. In the Client Component, useOptimistic shows the expected result immediately.
  3. The action validates input (see Validating Input), writes to the database, then calls revalidatePath or revalidateTag.
  4. The response carries fresh server-rendered UI, and the optimistic layer is replaced by the real data.
  5. If something failed, return an error state (see Building Forms with Server Actions) and the optimistic change vanishes by itself.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens to the optimistic state when the action's transition finishes?

    useOptimistic's layer is temporary. When the transition ends, the real state is shown, which is why failed requests roll back automatically.
  2. 2. When should addOptimistic be called?

    The point is instant feedback, so you call it first, then await the real work.
  3. 3. Why should redirect() not be wrapped in a try/catch that swallows errors?

    redirect throws an internal error that Next.js handles. A catch block that ignores it stops the redirect from happening.
  4. 4. What does revalidatePath('/chat') do inside a Server Action?

    It invalidates what is cached for that path, and Next.js can send the re-rendered page along with the action result.
  5. 5. Which of these is a poor fit for an optimistic update?

    Never pretend a payment succeeded. Optimism suits cheap, reversible actions.

Summary

  • An optimistic update shows the expected result immediately and lets the server's answer replace it.
  • useOptimistic(realState, reducer) returns a temporary layer over real state; it vanishes when the transition ends, so failures roll back automatically.
  • Call the optimistic setter before the await, and tell the user when something fails.
  • After a mutation, revalidatePath or revalidateTag mark data stale so Next.js returns fresh UI with the action response.
  • redirect() throws, so keep it outside swallowing try/catch blocks and call it last.
  • router.refresh() re-renders the current route from the server while keeping client state.

Next: Route Handlers