Sub topic 3
Marking Optimistic Items as Pending
Assume you know React function components, useState, props, async/await, and how a server request works. This chapter focuses on making optimistic results understandable and safe.
Show Which Items Are Pending
An optimistic item appears before the server confirms it. Mark it with a temporary field such as sending. This gives users feedback without hiding the item when the request is still running.
import { useOptimistic, useState } from "react";
export function Thread({ messages, sendMessage }) {
const [error, setError] = useState(null);
const [optimisticMessages, addOptimisticMessage] = useOptimistic(
messages,
(current, text) => [
...current,
{
id: crypto.randomUUID(),
text,
sending: true,
},
]
);
async function formAction(formData) {
const text = formData.get("message");
setError(null);
addOptimisticMessage(text);
try {
await sendMessage(text);
} catch {
setError("Could not send the message. Please try again.");
}
}
return (
<>
<ul>
{optimisticMessages.map((message) => (
<li key={message.id}>
{message.text}
{message.sending && <small> (Sending...)</small>}
</li>
))}
</ul>
{error && <p role="alert">{error}</p>}
<form action={formAction}>
<input name="message" required />
<button type="submit">Send</button>
</form>
</>
);
}The server-backed messages prop remains the source of truth. When the request succeeds and the parent supplies the updated messages, the temporary item is replaced by the real item. When the request fails, the optimistic item disappears when the Action ends. The error message explains the rollback.
Temporary IDs and Concurrent Updates
A temporary ID gives each optimistic item a stable React key. Generate it when creating the item, not while rendering. Avoid using the array index, because inserting or removing items can make React associate the wrong state with a row.
Several Actions can overlap. Each optimistic update is derived from the current optimistic list, so the reducer should append or transform data without mutating the existing array. Keep server responses ordered or reconcile them by ID when the server returns canonical data.
When to Avoid Optimistic Updates
Avoid this pattern when failure is common, the result cannot be predicted, or the operation has serious consequences, such as a payment or permission change. A loading indicator is clearer than showing a result that may be undone.
Exercise
Why should an optimistic list item have a temporary stable ID?
Show answer
React needs a stable key to track that item while it exists only on the client. The ID also helps reconcile it with the server's later response.