Sub topic 13
Pairing with useOptimistic
This chapter assumes you have read the earlier chapters. You should know how useActionState passes the previous state and FormData to an action, and how isPending works. You should also be comfortable with startTransition and with returning errors as state instead of throwing them.
The problem: waiting for the server feels slow
With useActionState, the screen shows the new state only after the action finishes. If the action calls a server and takes a second, the user types a message, presses Send, and sees nothing change for a second. The isPending flag can disable the button, but the list still has not changed.
An optimistic update fixes this. You show the expected result at once, before the server confirms it. If the server confirms, the real state arrives and replaces the guess. If the server fails, the guess disappears.
React provides useOptimistic for this. It does not replace useActionState. The two hooks do different jobs:
| Hook | Holds | Changes when |
|---|---|---|
| `useActionState` | The confirmed result of the last submission | The action finishes |
| `useOptimistic` | A temporary view of that result | You call its setter, and it reverts when the action finishes |
How useOptimistic works
The hook has this shape:
const [optimisticState, addOptimistic] = useOptimistic(state, updateFn);stateis the real value. Pass the confirmed state here.updateFn(currentState, value)is a pure function that returns the optimistic version. React calls it when you calladdOptimistic(value).optimisticStateis what you render. While no action is pending, it equalsstate.addOptimistic(value)appliesupdateFnon top of the real state.
The key rule is that the optimistic value lasts only while an action or transition is pending. When the transition ends, React drops the optimistic value and renders the real state again. You never have to undo anything yourself. If the action returned a new state that includes the saved item, the screen shows that item. If the action returned the old state, the item is gone.
Form actions already run inside transitions, so addOptimistic works inside them.
Combining the two hooks
The example below is a small chat form. The confirmed messages and any error live in useActionState. The optimistic list is derived from them.
import { useActionState, useOptimistic } from "react";
function deliver(text) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (text.toLowerCase().includes("fail")) {
reject(new Error("The server rejected the message."));
} else {
resolve({ id: crypto.randomUUID(), text });
}
}, 1000);
});
}
async function sendMessage(prev, formData) {
const text = String(formData.get("text") ?? "").trim();
if (!text) {
return { ...prev, error: "Type a message first." };
}
try {
const saved = await deliver(text);
return { messages: [...prev.messages, saved], error: null };
} catch (err) {
return { ...prev, error: err.message };
}
}
export function Chat() {
const [state, formAction] = useActionState(sendMessage, {
messages: [],
error: null,
});
const [messages, addOptimistic] = useOptimistic(
state.messages,
(current, message) => [...current, { ...message, sending: true }]
);
function submit(formData) {
const text = String(formData.get("text") ?? "").trim();
if (text) {
addOptimistic({ id: crypto.randomUUID(), text });
}
formAction(formData);
}
return (
<form action={submit}>
<ul>
{messages.map((m) => (
<li key={m.id} style={{ opacity: m.sending ? 0.5 : 1 }}>
{m.text}
{m.sending && " (sending...)"}
</li>
))}
</ul>
<input name="text" type="text" />
<button type="submit">Send</button>
{state.error && <p role="alert">{state.error}</p>}
</form>
);
}Four details in this code matter.
- The wrapper function.
useOptimisticneedsstatefromuseActionState, so it must be called after it. That means the action you pass touseActionStatecannot reachaddOptimistic. The fix is a small function,submit, defined inside the component. The form'sactionprop points to it. It callsaddOptimisticfirst and then passes the sameFormDatatoformAction. - The call order.
addOptimisticruns before anyawait. The wrapper runs inside the form's transition, and the call happens synchronously, so React knows which transition owns the optimistic value. - The marker field. The update function adds
sending: true. The component uses it to dim the item. Confirmed messages from the server do not have this field, so they render normally. - The id. The optimistic item gets a temporary id. The server's reply has a different id, so React treats the confirmed item as a new row. This is fine here, because the temporary row disappears in the same render.
The text input is uncontrolled, so React resets it when the action finishes, as you saw in the form reset chapter. The optimistic row stays visible because the optimistic value lives until the transition ends, not until the input resets.
What the user sees
The diagram shows the order of events for one successful submission.
If the server rejects the message, the last two steps change. The action returns { ...prev, error }. React drops the optimistic row, renders the old list, and shows the error text. The user sees the message appear and then vanish with an explanation.
Failure is a state, not an exception
The action above catches the error and returns it as state. This follows the rule from the validation chapter, and it matters more with optimistic updates. If the action throws, the error goes to the nearest error boundary and the component can unmount. The user then loses the typed text and the list. When you return the error as state, the optimistic row rolls back and the rest of the page stays intact.
Here is an improvement to consider. After a failure, the form resets, so the rejected text is gone from the input. If you want the user to retry without retyping, return the text in state, as in the first useActionState example. Then render it as the input's defaultValue.
Rapid submissions
Suppose the user sends "one" and then "two" before the first call finishes. Two things happen.
- Both optimistic rows are visible. Each call to
addOptimisticstacks on the previous one, in order. - The actions run one after another, as described in the queueing chapter. The second action receives the state returned by the first. That is why
sendMessagebuilds its result fromprev.messagesand not from a value captured earlier.
If the first message fails and the second succeeds, the result is correct. The first row disappears, the second becomes confirmed, and the error from the first is replaced by null when the second action returns. If you want to keep the first error visible, merge errors instead of overwriting them.
Pitfalls
- Calling
addOptimisticoutside a transition. React logs a warning, and the optimistic value does not persist as you expect. Form actions are safe. In anonClickhandler, wrap the call instartTransition, as you did when dispatching outside a form. - Calling it after an
await. Code after anawaitin an async action no longer runs inside the transition's synchronous scope. CalladdOptimisticat the top, before any async work. - Passing the wrong value as
state. The first argument must be the confirmed state. If you pass a list you already changed locally, the optimistic layer and your own changes will double up. - Impure update functions. React may call
updateFnmore than once, for example when it re-renders on top of a newer confirmed state. Do not generate ids or call APIs inside it. Create the id before callingaddOptimistic, as the example does. - Treating the optimistic value as saved. It is a guess. Do not use it to enable actions that need a server-confirmed id, such as a Delete button. Check the
sendingmarker and disable those controls for pending rows. - Using it for slow or risky work. Optimistic updates suit actions that nearly always succeed, like adding a comment or toggling a like. For payments or irreversible operations, use
isPendingand wait for the real result.
Summary of the pattern
- Hold the confirmed result in
useActionState. - Pass that result to
useOptimisticwith an update function that adds the expected item. - Render the optimistic value.
- Write a wrapper function that calls
addOptimisticfirst and thenformAction. - Put the wrapper on the form's
actionprop. - Return failures as state so the optimistic value rolls back cleanly.
Exercise
In the Chat example, the user sends the message "fail me". Describe what the list and the error area show during the one-second wait, and what they show afterward. Which line of code makes the optimistic row disappear?
Show answer
During the wait, the list shows "fail me (sending...)" at reduced opacity and there is no error text. After one second, deliver rejects, sendMessage catches the error, and the action returns { ...prev, error: "The server rejected the message." }. The transition ends, and React renders state.messages again, which does not contain the message. The row disappears and the alert shows the error. No line removes the row explicitly. It disappears because the returned state does not include it, and useOptimistic goes back to the real state when the transition finishes.
Exercise
A teammate moves the addOptimistic call below await deliver(text) inside the action, to be sure the server is reachable first. Why does this defeat the purpose of the hook?
Show answer
The optimistic row would appear only after the server has already replied, so the user gets no early feedback. Code after an await also runs outside the synchronous part of the transition, so React may not track the optimistic value correctly. Call addOptimistic before any await.