Sub topic 2
How the optimistic value is replaced by real state
Assume you know React function components, props, useState, and async/await. You should also know how an application sends data to a server.
How React replaces the optimistic value
useOptimistic does not permanently change your source of truth. It temporarily derives a value from real state while an Action is running.
When the Action finishes, React stops applying the optimistic update. The hook then uses the latest real state, usually supplied through props. If the server accepted the change, the parent should update that real state. If the request failed, the optimistic item disappears.
Form actions as the natural place to update optimistically
A form action is a function passed to a form's action prop. React runs it as an Action, so it is an appropriate place to call the optimistic setter and await the server request.
The example assumes sendMessage causes the parent to provide an updated messages prop after success.
Building an optimistic message list
The update function receives the current real or optimistic list and the value passed to the setter. It returns the next temporary view.
import { useOptimistic } from "react";
function Thread({ messages, sendMessage }) {
const [visibleMessages, addMessage] = useOptimistic(
messages,
(currentMessages, text) => [
...currentMessages,
{
id: crypto.randomUUID(),
text,
sending: true,
},
]
);
async function formAction(formData) {
const text = formData.get("message");
addMessage(text);
await sendMessage(formData);
}
return (
<>
<ul>
{visibleMessages.map((message) => (
<li key={message.id}>
{message.text}
{message.sending && <small> (Sending...)</small>}
</li>
))}
</ul>
<form action={formAction}>
<input name="message" required />
<button type="submit">Send</button>
</form>
</>
);
}crypto.randomUUID() gives the temporary item a stable key during rendering. After success, the server's message should replace it in messages. If the request fails and messages does not change, React removes the temporary item when the Action ends.
Exercise
What causes the optimistic message to disappear after a failed request?
Show answer
The real messages prop does not contain it, so React removes the optimistic update when the Action finishes.