How do you handle optimistic updates with Server Actions?

Use React's useOptimistic hook: render an optimistic copy of the state, update it immediately when the user acts (inside a transition or form action), then call the Server Function. When the action finishes and the server re-renders with real data, React replaces the optimistic state automatically; if the action throws, the optimistic change is discarded.

How useOptimistic works

  • const [optimistic, addOptimistic] = useOptimistic(serverState, (current, input) => next).
  • serverState comes from props (data rendered by a Server Component).
  • Call addOptimistic(input) inside an action or startTransition.
  • While the transition is pending, React shows optimistic. When it settles, it shows the new serverState.

Flow with Server Actions

  1. The user submits a form or clicks.
  2. addOptimistic updates the UI instantly (for example a new message marked "sending").
  3. The Server Function writes to the database and calls updateTag or revalidatePath.
  4. The response carries the fresh RSC payload; the parent re-renders with real data, and the optimistic state is dropped.

Handling errors

  • If the action throws, the optimistic state reverts. Show an error with useActionState state or a toast.
  • For actions that return errors rather than throwing, keep the optimistic item but mark it failed, with a retry button.

Good candidates

Likes, toggles, adding to lists, chat messages, reordering. Avoid it for operations users must trust exactly, such as payments.

Pitfalls

  • Optimistic items need temporary IDs for keys.
  • Calling addOptimistic outside a transition logs a warning and has no effect.

Code example

tsx
1// app/chat/thread.tsx
2"use client";
3
4import { useOptimistic, useRef } from "react";
5import { sendMessage } from "./actions"; // "use server": saves, then updateTag("thread:1")
6
7type Msg = { id: string; text: string; pending?: boolean };
8
9export function Thread({ messages }: { messages: Msg[] }) {
10 const formRef = useRef<HTMLFormElement>(null);
11 const [optimistic, addOptimistic] = useOptimistic(messages, (state: Msg[], text: string) => [
12 ...state,
13 { id: `temp-${crypto.randomUUID()}`, text, pending: true },
14 ]);
15
16 async function action(formData: FormData) {
17 const text = String(formData.get("text"));
18 addOptimistic(text); // instant UI
19 formRef.current?.reset();
20 await sendMessage(text); // server re-renders with real data afterwards
21 }
22
23 return (
24 <>
25 <ul>
26 {optimistic.map((m) => (
27 <li key={m.id} style={{ opacity: m.pending ? 0.5 : 1 }}>{m.text}</li>
28 ))}
29 </ul>
30 <form ref={formRef} action={action}>
31 <input name="text" required />
32 <button>Send</button>
33 </form>
34 </>
35 );
36}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app