Next.jsHard
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).serverStatecomes from props (data rendered by a Server Component).- Call
addOptimistic(input)inside an action orstartTransition. - While the transition is pending, React shows
optimistic. When it settles, it shows the newserverState.
Flow with Server Actions
- The user submits a form or clicks.
addOptimisticupdates the UI instantly (for example a new message marked "sending").- The Server Function writes to the database and calls
updateTagorrevalidatePath. - 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
useActionStatestate 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
addOptimisticoutside a transition logs a warning and has no effect.
Code example
tsx
1// app/chat/thread.tsx2"use client";34import { useOptimistic, useRef } from "react";5import { sendMessage } from "./actions"; // "use server": saves, then updateTag("thread:1")67type Msg = { id: string; text: string; pending?: boolean };89export 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 ]);1516 async function action(formData: FormData) {17 const text = String(formData.get("text"));18 addOptimistic(text); // instant UI19 formRef.current?.reset();20 await sendMessage(text); // server re-renders with real data afterwards21 }2223 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.