Sub topic 8
Optimistic UI with useOptimistic
This chapter assumes you can write React function components with useState, and that you know the Actions model from the earlier chapters. That means startTransition with an async function, isPending, and a function passed to <form action>. You should also be comfortable with FormData.
The problem: waiting for the server feels slow
A mutation such as sending a message, liking a post, or adding a todo takes a network round trip. If the UI waits for the server before showing the change, the interface feels sluggish even when everything works.
An optimistic update shows the expected result immediately, while the request is still running. If the request succeeds, the real data replaces the guess. If it fails, the guess disappears. React 19 provides the useOptimistic hook for this.
How useOptimistic works
const [optimisticState, setOptimistic] = useOptimistic(state, updateFn);stateis the real value. It usually comes from props or fromuseStatein a parent. It is the source of truth.updateFn(currentState, optimisticValue)is an optional pure function. It returns the temporary state to show. If you leave it out, the value you pass tosetOptimisticreplaces the state directly.optimisticStateis what you render. With no Action in flight, it equalsstate.setOptimisticstarts an optimistic update. You must call it inside an Action: a form action, or a function passed tostartTransition.
The key rule is that the optimistic value lasts only as long as the Action does. When the Action finishes, React discards the optimistic layer and renders whatever state is at that moment. You never write code to roll back. You only have to make sure the real state has been updated before the Action ends.
A message thread
This component renders a list of messages. When the user sends one, it appears immediately with a "Sending..." label.
import { useOptimistic, useRef } from "react";
export function Thread({ messages, sendMessage }) {
const formRef = useRef(null);
const [optimisticMessages, addOptimisticMessage] = useOptimistic(
messages,
(current, newText) => [
...current,
{ id: `pending-${current.length}`, text: newText, sending: true },
]
);
async function formAction(formData) {
const text = formData.get("message");
addOptimisticMessage(text);
formRef.current.reset();
await sendMessage(text);
}
return (
<div>
<ul>
{optimisticMessages.map((message) => (
<li key={message.id}>
{message.text}
{message.sending && <small> (Sending...)</small>}
</li>
))}
</ul>
<form action={formAction} ref={formRef}>
<input name="message" />
<button type="submit">Send</button>
</form>
</div>
);
}Four details matter here.
formActionis an Action. React runs it in a transition, so callingaddOptimisticMessageinside it is allowed.- The updater is pure. It builds a new array and does not mutate
current. - The optimistic item is marked. The
sending: trueflag lets the UI style pending items differently. The real items from the server do not have it. - The form is reset by hand. React resets uncontrolled form fields after a form Action finishes. That would leave the old text in the input for the whole request. Calling
reset()right away clears it at once.
The parent owns the real state
Thread does not store messages. The parent does, and it must update them before the Action ends.
import { startTransition, useState } from "react";
import { Thread } from "./Thread";
async function deliverMessage(text) {
await new Promise((resolve) => setTimeout(resolve, 1000));
if (text.toLowerCase().includes("fail")) {
throw new Error("Server rejected the message");
}
return { id: crypto.randomUUID(), text };
}
export function App() {
const [messages, setMessages] = useState([{ id: "m0", text: "Hello!" }]);
const [error, setError] = useState(null);
async function sendMessage(text) {
try {
const saved = await deliverMessage(text);
startTransition(() => {
setMessages((current) => [...current, saved]);
setError(null);
});
} catch (err) {
startTransition(() => {
setError("Your message could not be sent.");
});
}
}
return (
<div>
<Thread messages={messages} sendMessage={sendMessage} />
{error && <p role="alert">{error}</p>}
</div>
);
}sendMessage wraps its state updates in startTransition because it runs after an await. React tracks the transition only up to the first await, so later updates need their own startTransition to stay in the same low-priority batch.
Try typing a message containing the word "fail". The message appears with "Sending...", then disappears after one second, and the error shows. Any other message appears, loses its label, and stays, now with its server-assigned ID.
What happens on failure
Rollback is automatic, but a good failure experience is not. When the Action ends, whether it succeeded or not, the optimistic layer is dropped and the UI shows the real state. If the real state did not change, the optimistic item vanishes. Without more work, the user sees their message appear and then disappear with no explanation.
You are responsible for three things:
- Catch the error and store it in real state. In the example above,
setErrordoes this. Alternatively,useActionStatecan hold the error, as covered in the previous chapters. - Make sure the real state does not include the failed item. Update real state only after the server confirms.
- Keep the user's input recoverable. The example resets the form immediately, so a failed message is lost. For longer inputs, you could skip the early
reset()and clear the field only on success. Or you could store the failed text in the error state so the UI can offer to retry.
If your Action throws and nothing catches it, the error propagates to the nearest error boundary. The optimistic layer is still discarded.
The direct-value form
When the optimistic state is a simple replacement, such as a boolean, you can omit the updater. This is the common case for toggles.
import { startTransition, useOptimistic, useState } from "react";
async function saveLike(next) {
await new Promise((resolve) => setTimeout(resolve, 800));
return next;
}
function LikeButton({ liked, onChange }) {
const [optimisticLiked, setOptimisticLiked] = useOptimistic(liked);
function handleClick() {
const next = !optimisticLiked;
startTransition(async () => {
setOptimisticLiked(next);
await onChange(next);
});
}
return (
<button onClick={handleClick} aria-pressed={optimisticLiked}>
{optimisticLiked ? "Liked" : "Like"}
</button>
);
}
export function Post() {
const [liked, setLiked] = useState(false);
async function handleChange(next) {
const saved = await saveLike(next);
startTransition(() => setLiked(saved));
}
return <LikeButton liked={liked} onChange={handleChange} />;
}Here setOptimisticLiked(next) replaces the value directly. The button flips at once. About 800 ms later, liked changes in the parent and the Action ends, so the optimistic layer and the real value agree.
Note that handleClick reads optimisticLiked, not liked. During a pending Action, a second click should toggle from what the user currently sees.
Rules and behavior to keep in mind
Optimistic setters work only inside Actions
If you call the setter outside a transition or form action, React logs a warning. The temporary value would also be dropped almost immediately. Wrap the call in startTransition or put it inside a form action.
The updater is replayed on top of new state
If the real state changes while an Action is pending, React recomputes the optimistic value by applying your updater to the new state. So two things follow:
- The updater must be pure and must depend only on its arguments.
- If an unrelated update arrives mid-request, such as another user's message, it shows up together with your pending item.
Multiple pending updates stack
If the user submits twice before the first Action ends, both optimistic updates apply in order. That is why the Thread example builds IDs from current.length, so the pending items get distinct keys. Use stable, unique keys in real code, for example a client-generated UUID that you send to the server and reuse as the real ID.
Optimistic state is not a store
The optimistic value is local to the component that calls the hook. Siblings and parents do not see it unless you pass it down. Keep the hook in the lowest component that needs the temporary value.
Common mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| Warning that an optimistic update happened outside a transition | Setter called from a plain event handler or timer | Wrap in `startTransition` or use a form action |
| Optimistic item flashes, vanishes, then the real item appears | Real state updated after the Action ended | Update real state before the Action's function returns |
| Optimistic item disappears with no message | Error caught but not shown, or never caught | Store an error in real state and render it |
| Optimistic list is mutated or duplicated | Updater uses `push` or reads outside values | Return a new array from arguments only |
| Duplicate React key warnings | Pending IDs collide | Use a unique client-generated ID |
| Real state update after `await` renders late | Missing `startTransition` after the `await` | Wrap the update in `startTransition` |
When not to use it
Optimistic UI is a poor fit when the outcome is uncertain or costly to reverse. A payment, an irreversible delete, or an action with frequent server-side rejection should show a clear pending state instead. Use isPending from useTransition, or pending from useFormStatus. A wrong guess that appears and then reverses erodes trust more than a short wait does.
Exercise
In the LikeButton example, the server request takes 800 ms and fails. Nothing catches the error. Describe what the user sees, and name the two changes that would make the failure understandable.
Show answer
The button flips to "Liked" immediately. When the Action ends, the optimistic layer is dropped, and because liked never changed, the button returns to "Like" with no explanation. The uncaught error also goes to the nearest error boundary. The fixes are to catch the error in handleChange and store a message in real state, and to render that message near the button (for example with role="alert").
Exercise
Why does LikeButton compute next from optimisticLiked rather than from the liked prop? What would go wrong if it used liked?
Show answer
During a pending Action, optimisticLiked is what the user sees. If the user clicks twice quickly, the second click should reverse the displayed value. Using liked would compute the same next for both clicks, because liked has not changed yet. The second click would then request the same state again, and the UI would not toggle back.