Sub topic 1
Optimistic UI with `useOptimistic`
Prerequisites
This chapter assumes you know React function components, props, useState, and JavaScript async/await. You should also understand that a server request can succeed or fail.
What an optimistic update is and why it helps
An optimistic update changes the interface before the server confirms the change. The interface predicts success, so it feels immediate. When a user sends a message, the message can appear at once instead of waiting for the network.
This approach trades certainty for speed. If the request fails, the interface must return to the last confirmed state and explain the failure.
sequenceDiagram
participant U as User
participant R as React
participant S as Server
U->>R: Submit message
R-->>U: Show message immediately
R->>S: Send request
S-->>R: Confirm or reject
R-->>U: Keep message or revert itActions and transitions: the context `useOptimistic` works in
React Actions are functions that perform an update and can include asynchronous work. A transition is React's way to mark an update as non-urgent. useOptimistic is designed for this context: its setter should run inside a form action, a server action, or startTransition.
React displays the optimistic value while the Action is pending. When the Action finishes, React uses the confirmed state supplied by the component.
> callout tip > An optimistic update is a display prediction, not a replacement for saving data. The server remains the source of truth.
The `useOptimistic` hook: state in, optimistic state out
The basic form receives real state and returns an optimistic state plus a setter:
const [optimisticLiked, setOptimisticLiked] = useOptimistic(liked);The first value, liked, is the confirmed state. The second value is what React displays during the Action. Calling the setter supplies the temporary value.
Deriving optimistic state with an update function
For lists or objects, pass an update function. This function receives the current optimistic state and an input value, then returns the next optimistic state.
import { startTransition, useOptimistic } from "react";
function Thread({ messages, sendMessage }) {
const [optimisticMessages, addOptimisticMessage] = useOptimistic(
messages,
(current, text) => [
...current,
{ id: crypto.randomUUID(), text, sending: true },
],
);
function submit(text) {
startTransition(async () => {
addOptimisticMessage(text);
await sendMessage(text);
});
}
return (
<>
<ul>
{optimisticMessages.map((message) => (
<li key={message.id}>
{message.text}
{message.sending && " (Sending...)"}
</li>
))}
</ul>
<button onClick={() => submit("Hello")}>Send</button>
</>
);
}The update function keeps the existing messages and appends a temporary one. The real messages prop must later contain the confirmed message.
Exercise
What does the update function receive, and what must it return?
Show answer
It receives the current optimistic state and the setter's input. It returns the next optimistic state.