Sub topic 7
Building an optimistic message list
This chapter combines the pieces from earlier chapters into one working feature: a message thread where a sent message appears at once, before the server confirms it.
It assumes you know React function components and useState, how to pass props and lift state up, and async/await. It also assumes you have seen the useOptimistic signature and the idea that an Action is an async function run inside a transition.
What we are building
The feature has two components.
Appowns the real list of messages and talks to the "server".Threadshows the list and the form. It usesuseOptimisticto display the real list plus any message that is still being sent.
The split matters. useOptimistic does not store anything permanent. The real state stays in the parent (it could also come from a router, a data library, or a server component). Thread only decides what to display while a request is in flight.
The flow of one submission
Two points in this sequence are easy to miss:
- The optimistic message is added before the
await. If you add it after the server responds, there is nothing optimistic about it. - React does not remove the optimistic message at a specific step. It drops the optimistic layer when the Action finishes, and the list is then derived from the real
messagesprop again.
The complete example
This is a runnable version. The fake server waits one second and then returns a message with a server-assigned id.
import { useOptimistic, useState } from "react";
function saveMessageOnServer(text) {
return new Promise((resolve) => {
setTimeout(() => {
resolve({ id: crypto.randomUUID(), text });
}, 1000);
});
}
export default function App() {
const [messages, setMessages] = useState([
{ id: "m1", text: "Hello there" },
]);
async function sendMessage(text) {
const saved = await saveMessageOnServer(text);
setMessages((current) => [...current, saved]);
}
return <Thread messages={messages} sendMessage={sendMessage} />;
}
function Thread({ messages, sendMessage }) {
const [optimisticMessages, addOptimisticMessage] = useOptimistic(
messages,
(currentMessages, newMessage) => [
...currentMessages,
{ ...newMessage, sending: true },
]
);
async function formAction(formData) {
const text = formData.get("message");
addOptimisticMessage({ id: crypto.randomUUID(), text });
await sendMessage(text);
}
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>
</>
);
}Run it in any React 19 project and send a message. The text appears immediately with "(Sending...)". One second later the label disappears, because the real list now contains the saved message.
Walking through the code
The real state and the server call
App holds messages in useState. Its sendMessage function awaits the server and then appends the saved message to the real list. The order matters. The real state must be updated before sendMessage returns, because the Action ends when its promise settles. At that moment React stops showing the optimistic list. If the real list has not yet been updated, the message would vanish and reappear a moment later.
The update function
useOptimistic(messages, updateFn) returns two things. The first is the value to render. The second is a setter, which this example calls addOptimisticMessage.
When you call the setter with an argument, React calls your update function as updateFn(currentState, argument). Here currentState is the real messages prop (plus any earlier optimistic updates still pending), and argument is the object we passed. The function returns the new list to display.
Keep the update function pure. It should only compute a new array from its inputs. That is why the example creates the temporary id in formAction and passes it in. If the update function called crypto.randomUUID() itself, the same update could produce different ids each time React ran it. React may call update functions more than once, for example in Strict Mode during development or when it re-derives state after the real state changes.
The form action
Passing a function to <form action={...}> is new in React 19. React calls the function with a FormData object when the form is submitted, and it runs the function inside a transition. That transition is what the optimistic state depends on. Because formAction is already inside an Action, you can call addOptimisticMessage in it without wrapping anything yourself.
Two other things happen without extra code:
- The browser's default page reload is prevented.
- After the Action succeeds, React resets uncontrolled form fields, so the input empties on its own. You do not need
useRefor a controlled input to clear it.
Reading the input
formData.get("message") reads the value by the input's name attribute. The name is required. An input without a name is not included in FormData.
The pending marker
The reducer adds sending: true to the optimistic message, and the list item renders "(Sending...)" when that flag is set. Real messages from the server do not have the flag, so the label disappears when the real item replaces the optimistic one.
This is a general technique. The optimistic layer can add any field that helps the UI: a dimmed style, a spinner, a disabled delete button. Because the flag exists only in the optimistic copy, it cannot leak into your real data.
Timeline of the state
The table shows what each value holds at each moment, assuming a thread that starts with one message and a user who sends "Hi".
| Moment | Real `messages` | `optimisticMessages` |
|---|---|---|
| Before submit | `[Hello there]` | `[Hello there]` |
| After `addOptimisticMessage`, request in flight | `[Hello there]` | `[Hello there, Hi (sending)]` |
| Server responded, parent updated real state | `[Hello there, Hi]` | `[Hello there, Hi]` |
| Action finished | `[Hello there, Hi]` | `[Hello there, Hi]` |
messages never contains the pending item. Only the derived list does. This is also why a failed request needs no cleanup code to remove the item, a point the chapter on failures covers in detail.
Common mistakes
Calling the setter outside an Action
React warns when you call the optimistic setter outside an Action or transition. In an onClick handler, for example, the update would have no defined end, so React cannot know when to revert it. Use a form action, or wrap the code in startTransition(async () => { ... }).
Forgetting to update the real state
If sendMessage succeeds but never updates messages, the optimistic message shows while the request runs and then disappears. React is behaving correctly: the real state never contained the message. The fix is in the parent, not in useOptimistic.
Mutating the current state
The update function receives the current array. Return a new array with spread or concat. Calling currentMessages.push(...) mutates state that React still holds and produces bugs that are hard to trace.
Reusing the temporary id as the real id
The optimistic message has a temporary id, and the server returns a message with a different id. React sees a different key, so it unmounts the optimistic <li> and mounts a new one. That is harmless in this simple list. It matters if each item has its own state or animation. You can avoid the remount by letting the client generate the id and having the server accept it. The later chapter on temporary ids and keys covers this.
Extending the example
Two small changes are worth making to a real feature.
Disable empty submissions. Check text.trim() at the top of formAction and return early. Do this before calling addOptimisticMessage, otherwise an empty message flashes on screen.
Show a pending state on the form itself. The useFormStatus hook, called from a component rendered inside the form, tells you whether the form is submitting. You can use it to disable the Send button. It complements the per-message marker and does not replace it.
Summary
- Keep real state in a parent, a router, or a data layer.
useOptimisticonly produces a display copy. - Call the setter at the start of a form action or a
startTransition, before awaiting. - Make the update function pure. Generate random ids outside it.
- Update the real state before the Action's promise resolves, so the swap from optimistic to real is seamless.
- Add a flag such as
sending: truein the update function to mark pending items.
Exercise
In the message list above, a teammate moves addOptimisticMessage({ id: crypto.randomUUID(), text }) to the line after await sendMessage(text). What changes for the user, and why is it a problem for the purpose of the feature?
Show answer
The message no longer appears immediately. The user waits for the whole server round trip before anything shows up, so the UI behaves like an ordinary non-optimistic form. In addition, by that point the parent has already added the real message, so the optimistic call adds a second copy that is displayed until the Action finishes. The setter must be called before the await.
Exercise
The update function in Thread calls crypto.randomUUID() itself instead of receiving the id from formAction. Why is this a bad idea even if the example appears to work?
Show answer
Update functions must be pure, because React can call them more than once, for example in Strict Mode or when it re-derives the optimistic state after the real state changes. Each call would produce a different id, so the item's key could change between renders and React would remount the list item. Generating the id in the action and passing it in keeps the update function deterministic.