Sub topic 5
How the optimistic value is replaced by real state
This chapter assumes you know useState, props, and async/await. It also assumes you have met useOptimistic and Actions in earlier chapters. The goal here is to explain one behavior: you never write code that undoes an optimistic update. React discards it for you, and knowing when it does so explains most surprises with this hook.
The optimistic value is temporary
useOptimistic(state, updateFn) returns two things. The first is the value to render. The second is a setter that adds an optimistic change.
The key rule is that the optimistic value exists only while an Action is pending. An Action is an async function that React runs inside a transition, such as a form action or an async startTransition callback.
While the Action is pending, React renders the optimistic value. When the Action finishes, React renders whatever state is at that moment.
The hook does not store your optimistic change. It recomputes the result on each render from the current state and any pending optimistic updates.
The lifecycle
The sequence below shows what happens when a user submits a message.
Two things must both be true for the final list to be correct. The Action must finish, and the real state passed into the hook must contain the saved data.
Reading the revert in code
Here is a small component that makes the behavior visible. The parent owns the real list, and the child adds an optimistic entry.
import { useOptimistic, useState } from "react";
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
export default function App() {
const [messages, setMessages] = useState([{ id: 1, text: "Hello" }]);
async function sendMessage(text) {
await delay(1500);
setMessages((current) => [...current, { id: Date.now(), text }]);
}
return <Thread messages={messages} sendMessage={sendMessage} />;
}
function Thread({ messages, sendMessage }) {
const [optimisticMessages, addOptimisticMessage] = useOptimistic(
messages,
(current, text) => [...current, { id: "temp-" + text, text, sending: true }]
);
async function formAction(formData) {
const text = formData.get("message");
addOptimisticMessage(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>
</>
);
}Follow the timeline after the user submits "Hi".
addOptimisticMessage("Hi")runs. The list shows "Hello" and "Hi (Sending...)".- For 1.5 seconds the Action is pending, and the optimistic entry stays visible.
setMessagesadds the real "Hi" to the parent state.- The Action ends. React drops the optimistic layer and renders
messages, which now holds the real entry.
The "Sending..." label disappears because the new item is a different object without sending: true. Nobody removed the old one.
The revert is a replacement, not a rollback command
React does not compare the optimistic value with the real one. It simply stops using the optimistic one. This leads to three behaviors worth remembering.
- Success and failure look the same to React. If the Action ends and
messagesdid not change, the optimistic item vanishes. A failed request therefore needs no cleanup code, but it does need an error message so the user knows why the item disappeared. - The real state must be updated before the Action ends. If you update the parent state after
awaithas returned and the Action has already completed, the list can briefly show the old data. Keep the state update inside the awaited work, assendMessagedoes above. - Changes to
stateduring the Action also take effect. If the realstateprop changes while the Action is pending, the hook reapplies your optimistic updates on top of the new value. The optimistic layer always sits above the latest real state.
Common mistakes
- Calling the setter outside an Action. If you call it from a plain event handler without
startTransition, there is no Action to tie it to, and React warns that an optimistic update happened outside a transition or Action. - Not awaiting the server call. Without
await, the Action ends at once, and the optimistic item disappears before the request completes. - Expecting the optimistic value to persist. If the parent never updates
messages, the item will not stay. The hook does not keep data. Your real state does.
Exercise
A component calls the optimistic setter, then runs await fetch(...) in a form action. The request succeeds, but the parent never updates its messages state. What does the user see when the Action finishes, and why?
Show answer
The optimistic item disappears. When the Action ends, React stops using the optimistic value and renders the real state. Since the parent never added the saved message to messages, the real list does not contain it. The fix is to update the real state, for example by calling the parent's setter or refetching the data, before the Action completes.
Exercise
Why does a failed request need no rollback code in the component, and what should you add instead?
Show answer
React discards the optimistic value when the Action ends, and a failure leaves the real state unchanged, so the list returns to its previous contents by itself. You should add an error message, for example in a catch block, so the user understands why the item they saw disappeared.