Sub topic 7
Building an optimistic message list
This chapter assumes you know useState, props, async/await, and the basics of useOptimistic and form actions from the earlier chapters. Here you combine them into one working message thread.
What we are building
The thread shows saved messages. When the user submits the form, the new message appears at once, marked "Sending...". About a second later the server confirms it, and the pending marker disappears.
The work is split between two components:
- The parent owns the real
messagesstate and the function that talks to the server. Threadowns the optimistic view of that state and the form.
The parent: real state and the server call
The parent never sees optimistic data. It saves the message and then updates the real list.
import { useState } from "react";
function saveOnServer(text) {
return new Promise((resolve) => {
setTimeout(() => resolve({ id: crypto.randomUUID(), text }), 1000);
});
}
export default function ThreadPage() {
const [messages, setMessages] = useState([
{ id: "m1", text: "Welcome to the thread." },
]);
async function sendMessage(formData) {
const saved = await saveOnServer(formData.get("message"));
setMessages((current) => [...current, saved]);
}
return <Thread messages={messages} sendMessage={sendMessage} />;
}saveOnServer stands in for a real fetch call. It resolves after one second with a message that has a server-assigned id.
The child: optimistic state and the form action
import { useOptimistic } from "react";
function Thread({ messages, sendMessage }) {
const [optimisticMessages, addOptimisticMessage] = useOptimistic(
messages,
(currentMessages, text) => [
...currentMessages,
{ id: crypto.randomUUID(), text, sending: true },
]
);
async function formAction(formData) {
addOptimisticMessage(formData.get("message"));
await sendMessage(formData);
}
return (
<>
<ul>
{optimisticMessages.map((m) => (
<li key={m.id}>
{m.text}
{m.sending && <small> (Sending...)</small>}
</li>
))}
</ul>
<form action={formAction}>
<input type="text" name="message" />
<button type="submit">Send</button>
</form>
</>
);
}The first argument to useOptimistic is the real messages prop. The second is the update function. It receives the current list and the value passed to addOptimisticMessage, and it returns the list to display.
What happens on each submit
Passing formAction to <form action> makes React run it as an Action inside a transition. That is why calling addOptimisticMessage there is allowed.
- The user submits.
addOptimisticMessageruns, and React renders the list with the extrasending: trueitem. await sendMessage(formData)keeps the Action open while the server works.- The parent calls
setMessageswith the saved message. - The Action finishes. React stops using the optimistic value and renders from the new
messagesprop.
The optimistic message is never removed by your code. It exists only while the Action is pending, so nothing needs cleanup.
Details that matter
The pending marker comes from the update function. You add sending: true there, and the real message from the server has no such field, so the marker disappears when the real list takes over.
The temporary id from crypto.randomUUID() gives React a stable key during the optimistic phase. When the real list arrives, the server's id differs, so React treats the item as a new one. That is harmless for plain text. For items with local state, such as an open editor, you would need to keep the same key across both phases.
Common mistakes
| Mistake | Result |
|---|---|
| Updating `messages` in the parent before the server responds | The real state is no longer real, and a failed request cannot revert on its own |
| Mutating `currentMessages` with `push` | The real list is corrupted, and the revert shows the wrong data |
| Forgetting to `await` the server call | The Action ends at once, and the optimistic message vanishes before the real one arrives |
| Using the array index as the key | Keys shift when the real list replaces the optimistic one |
The failure path, where the request rejects, is covered in the next chapters on error handling.
Exercise
In the example, suppose you remove await from await sendMessage(formData) so the Action returns right away. What does the user see, and why?
Show answer
The message flashes on screen and then disappears until the server responds. Without await, the Action ends immediately, so React discards the optimistic value and renders the old messages prop. When setMessages runs about a second later, the real message appears. The Action must stay pending until the real state has been updated.