Sub topic 13
Pairing with useOptimistic
This chapter assumes you know how useActionState returns the next state from an action, and how isPending reports a submission in progress. Here you add useOptimistic, which shows the expected result right away instead of waiting for the server.
The problem: waiting for the round trip
With useActionState, the new state arrives only after the action finishes. If saving takes a second, the list stays unchanged for that second. A pending button tells the user something is happening, but it does not show them the result.
useOptimistic lets you display the likely result immediately. When the action finishes, React discards the temporary value and shows the real state.
The useOptimistic signature
const [optimisticState, addOptimistic] = useOptimistic(state, updateFn);stateis the real value. It is usually the state returned byuseActionState.updateFn(currentState, optimisticValue)returns the temporary state to display.addOptimistic(value)applies the update. Call it inside an action or a transition, so React knows when to drop it.
The optimistic value is never stored. It exists only while the surrounding action is pending. When the action ends, React re-renders from the real state.
Worked example: an optimistic shopping list
The list below keeps real items in useActionState and shows a temporary entry while the save runs.
import { useActionState, useOptimistic } from "react";
const save = (name) => new Promise((resolve) => setTimeout(resolve, 1000));
export function ShoppingList() {
const [items, formAction] = useActionState(addItem, []);
const [optimisticItems, addOptimistic] = useOptimistic(
items,
(current, name) => [...current, { name, sending: true }]
);
async function addItem(prevItems, formData) {
const name = String(formData.get("name") ?? "").trim();
if (!name) return prevItems;
addOptimistic(name);
await save(name);
return [...prevItems, { name, sending: false }];
}
return (
<form action={formAction}>
<input name="name" type="text" />
<button type="submit">Add</button>
<ul>
{optimisticItems.map((item, i) => (
<li key={i} style={{ opacity: item.sending ? 0.5 : 1 }}>
{item.name}
</li>
))}
</ul>
</form>
);
}Three details matter here:
addItemis declared inside the component, so it can calladdOptimistic. Function declarations are hoisted, souseActionStatecan reference it above the definition.addOptimisticis called before the firstawait. React ties the optimistic update to the action that is running at that moment.- The render uses
optimisticItems, notitems. Usingitemswould hide the temporary entry.
What happens during a submission
If save throws, or the action returns the previous state, the optimistic item disappears. The user sees the list return to what it was. For expected failures, such as validation, return an error in the state and render it. Then the user learns why the item vanished.
Common mistakes
- Calling
addOptimisticoutside an action or transition. React warns, and the value may not revert correctly. Calls inside a form action are safe. - Rendering the real state. The optimistic value only appears if you render the first value returned by
useOptimistic. - Expecting the optimistic value to persist. It always reverts. Anything that must stay belongs in the state the action returns.
- Using the index as a key. This is fine for a demo. In real code, give items an id so React keeps the right row when the optimistic entry is replaced.
Exercise
In the shopping list example, the user submits "Milk" and the server save fails by throwing an error. What does the list show after the action ends, and why?
Show answer
The list returns to the previous items, without "Milk". The optimistic entry exists only while the action is pending. When the action ends, React renders from the real state again, and the real state never received "Milk". To explain the failure to the user, catch the error and return an error message in the state.