Sub topic 8
Optimistic UI with useOptimistic
This chapter assumes you know React function components, useState, form action props with FormData, and the Action model from earlier chapters. An Action is an async function that React runs inside a transition.
Why show a result before the server replies
A mutation takes time. If the UI waits for the server before it shows anything, the app feels slow. Optimistic UI shows the expected result right away and corrects it if the request fails.
useOptimistic is the React 19 hook for this. It gives you a copy of some state that you can change temporarily while an Action runs. When the Action finishes, React discards the temporary value and shows the real state again.
The shape of the hook
const [optimisticValue, addOptimistic] = useOptimistic(value, reducer);valueis the real state. It usually comes from props or from a parent that fetches data.reduceris an optional function(current, input) => next. It computes the optimistic value from the current value and whatever you pass toaddOptimistic.optimisticValueequalsvaluewhen no Action is running. While one runs, it holds the result of the reducer.addOptimistic(input)sets the temporary value.
You must call addOptimistic inside an Action, such as a form action or a function passed to startTransition. Outside one, React warns you, and the update does not behave as intended.
A worked example: a message thread
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>
);
}Follow what happens when the user submits:
- React calls
formActionwith the form'sFormData. addOptimisticMessage(text)runs the reducer. The list now contains a new item markedsending: true, and the UI shows it immediately.formRef.current.reset()clears the input. Callingresetyourself lets the field empty at once, instead of waiting for the Action to finish.await sendMessage(text)sends the data. The optimistic item stays on screen during this time.- When the Action ends, the optimistic state is dropped. The parent has passed down a new
messagesprop that includes the saved message, so the item is replaced by the real one.
The sending flag is how you tell the user which items are not yet confirmed. You can use it to dim the text, show a spinner, or disable a delete button.
What happens when the request fails
If the Action throws or the parent never adds the item to value, the optimistic value disappears when the Action ends. The UI snaps back to the real state. The user sees their message vanish with no explanation.
To avoid that, catch the failure and report it. Use state you control, such as the result from useActionState, to display an error message. The optimistic item still disappears, but the user knows why. You can also return the unsent text so the input can be refilled.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Calling `addOptimistic` outside an Action | A warning, and the optimistic value does not behave as intended | Call it inside a form action or `startTransition` |
| Never updating the real `value` after success | The optimistic item vanishes and nothing replaces it | Update the source state or refetch data when the Action succeeds |
| Using a non-unique `key` for pending items | React may mix up list items | Give pending items a distinct id, as `pending-${current.length}` does above |
| Swallowing errors silently | The item disappears with no explanation | Show an error with `useActionState` or your own state |
When to use it
Use optimistic updates when success is very likely and a delay would be noticeable: sending a chat message, toggling a like, adding a todo. Avoid them when failure is common or the outcome is hard to predict, such as payments, where showing a false success misleads the user.
Exercise
A user submits a message, sees it appear with "(Sending...)", and then the request fails. What does the user see after the Action ends, and what should you add so the failure is clear?
Show answer
The optimistic item disappears because React drops the temporary value and shows the real messages state again. Add error handling, for example catch the failure and store an error message with useActionState, then render it so the user knows the message was not sent.
Exercise
Why must addOptimisticMessage(text) be called inside the form action rather than in a plain click handler outside any transition?
Show answer
The optimistic value only lasts for the duration of an Action. Inside one, React knows when the Action finishes and drops the temporary value at that point. Outside an Action, React has no end point to revert at, so it warns and the update does not behave as intended.