Sub topic 8
Marking items as pending
This chapter assumes you know useState, props, and async/await. It also assumes you have read the earlier chapters on the useOptimistic update function, the automatic revert, and form actions. Here you will learn how to show users which list items are still unconfirmed.
Why an optimistic item needs a visible state
An optimistic item looks identical to a confirmed one unless you mark it. If the request is slow, the user sees a message in the list and assumes it was delivered. A few seconds later it may vanish, and they get no explanation. A small pending marker shows that the item is provisional. It is often a dimmed row or a "Sending..." label.
React gives you no built-in "this item is optimistic" flag. The optimistic list is an ordinary array that your update function builds. You add the marker yourself, as a field on the optimistic item.
The pending flag lives in the update function
The update function is the one place that creates optimistic items. Putting the flag there keeps the marker and the item in sync.
(currentMessages, newMessage) => [
...currentMessages,
{ ...newMessage, pending: true },
]Items from the real messages prop have no pending field, so message.pending is undefined and falsy. You never have to clear the flag. When the Action finishes, React discards the optimistic list and renders the real one. The real list contains no pending fields, so every marker disappears with it.
That empty fence is a mistake, so ignore it. The diagram for this chapter follows.
Keep the reducer pure: build the item in the action
A common mistake is to generate the temporary ID inside the update function. React may call that function more than once for the same update, for example in Strict Mode during development. A call to crypto.randomUUID() there can produce a different ID on each call, so the item's key changes between renders.
Instead, build the item in the action and pass the whole item to the setter. The update function then only appends the item and sets the flag.
const [optimisticMessages, addOptimisticMessage] = useOptimistic(
messages,
(currentMessages, newMessage) => [
...currentMessages,
{ ...newMessage, pending: true },
]
);
async function formAction(formData) {
addOptimisticMessage({
id: `temp-${crypto.randomUUID()}`,
text: formData.get("message"),
});
await sendMessage(formData);
}The temp- prefix makes temporary IDs easy to recognize while debugging. The later chapter on temporary IDs and keys covers key stability in detail.
A complete working example
This example runs as one file in a React 19 project. The fake server call waits 1.5 seconds, which makes the pending state easy to observe.
import { startTransition, useOptimistic, useState } from "react";
function fakeServerSave(text) {
return new Promise((resolve) => {
setTimeout(() => resolve({ id: crypto.randomUUID(), text }), 1500);
});
}
function MessageItem({ message }) {
return (
<li
className={message.pending ? "message pending" : "message"}
aria-busy={message.pending ? "true" : "false"}
>
{message.text}
{message.pending && <small> (Sending...)</small>}
</li>
);
}
function Thread({ messages, sendMessage }) {
const [optimisticMessages, addOptimisticMessage] = useOptimistic(
messages,
(currentMessages, newMessage) => [
...currentMessages,
{ ...newMessage, pending: true },
]
);
async function formAction(formData) {
const text = formData.get("message");
addOptimisticMessage({ id: `temp-${crypto.randomUUID()}`, text });
await sendMessage(text);
}
return (
<>
<ul>
{optimisticMessages.map((m) => (
<MessageItem key={m.id} message={m} />
))}
</ul>
<form action={formAction}>
<input type="text" name="message" required />
<button type="submit">Send</button>
</form>
</>
);
}
export default function App() {
const [messages, setMessages] = useState([
{ id: "1", text: "Hello there" },
]);
async function sendMessage(text) {
const saved = await fakeServerSave(text);
startTransition(() => {
setMessages((current) => [...current, saved]);
});
}
return <Thread messages={messages} sendMessage={sendMessage} />;
}The parent wraps its setMessages call in startTransition because it runs after an await. React only tracks the Action's updates automatically up to the first await. Wrapping the later update keeps it in the same transition, so the real list and the end of the optimistic state render together. Without this, you can see a flash where the item briefly disappears.
Add styling for the pending class:
.message.pending {
opacity: 0.6;
font-style: italic;
}What the user sees
- The user submits the form. The input clears and the new message appears dimmed with "(Sending...)".
- About 1.5 seconds later the server call finishes. The parent stores the saved message.
- React renders the real list. The message appears at full opacity and the label is gone.
The pending state exists exactly as long as the Action runs.
Choosing how to show pending
You have several ways to mark an item. Pick based on how much the user needs to know.
| Marker | Good for | Cost |
|---|---|---|
| Dimmed text or reduced opacity | Chat, comments, to-do items | Low-contrast text can hurt readability, so check contrast |
| "Sending..." label | Cases where the delay might be long | Adds text that must be cleaned up and translated |
| Small spinner or clock icon | Dense lists such as tables | Needs an accessible name, since an icon alone says nothing to a screen reader |
| Disabled controls on the item | Items that offer actions such as delete or edit | Users may wonder why the buttons are disabled, so pair it with another marker |
Do not rely on color or opacity alone. Some users cannot perceive the difference. A text label or an aria-busy attribute covers them.
Disabling actions on pending items
A pending item has no real ID yet. The server does not know about it. If the user clicks "Delete" on that row, your handler would send temp-... to a server that has no such record.
Disable actions that need a real ID:
function MessageItem({ message, onDelete }) {
return (
<li className={message.pending ? "message pending" : "message"}>
{message.text}
<button
type="button"
disabled={message.pending}
onClick={() => onDelete(message.id)}
>
Delete
</button>
</li>
);
}The same applies to editing, reordering, and any request that references the item. The pending flag gives you a single condition to check.
Announcing changes to assistive technology
Dimming a row says nothing to a screen reader. Two small additions help:
aria-busy="true"on the pending item tells assistive technology that the content is still changing.- A live region announces the outcome. If you have a status element with
role="status", update its text when the Action completes.
Keep announcements short. For a chat, announcing every send can be noisy, so you may announce only failures. The error example in the earlier chapter already uses role="alert" for that case.
Pending flag, `useFormStatus`, and `useTransition`
React offers other pending signals. They answer different questions, so do not substitute one for another.
| Signal | Scope | Use it to |
|---|---|---|
| `pending` field on an item | One list item | Style or disable a single optimistic row |
| `useFormStatus().pending` | The enclosing form | Disable the submit button while the form's action runs |
| `useTransition()` `isPending` | One transition you started | Show a general busy indicator for a non-form interaction |
useFormStatus must be called from a component rendered inside the <form>, not from the component that renders the form. A per-item flag is the only one of the three that distinguishes row A from row B when several submissions are in flight.
import { useFormStatus } from "react-dom";
function SubmitButton() {
const { pending } = useFormStatus();
return (
<button type="submit" disabled={pending}>
{pending ? "Sending..." : "Send"}
</button>
);
}Disabling the submit button blocks a second submission while one is running. Whether you want that depends on your design. A chat usually lets people keep typing, so you would leave the button enabled.
Edge cases and gotchas
- Do not store
pendingin real state. The flag belongs only in the update function's output. If you copy optimistic items intouseState, the flag outlives the request and the item stays dimmed forever. - Do not check for
pendingto decide data correctness. It is a display hint. Server data should never depend on it. - Failure removes the item and its marker together. When the request fails and the real list does not change, the optimistic item vanishes. If you want a visible "failed" row with a retry button, keep that item in your own state, separate from the optimistic list, as the error-handling chapter discusses.
- A new key causes a remount. The optimistic item has a key like
temp-abc. The saved item has the server's ID. React sees a different key and unmounts the old row, then mounts a new one. Local state inside the row, such as focus or an open menu, is lost. If that matters, return a stable client-generated ID from your server and reuse it. - A slow row can look stuck. If a request takes much longer than expected, a dimmed row with no explanation looks broken. Consider adding a timeout message for long requests.
- Pending items appear last. The reducer shown here appends. If your real list sorts newest first, prepend instead so the optimistic row appears where the saved row will land. Otherwise the row jumps when it is confirmed.
Summary of the pattern
- Create the optimistic item in the action, including its temporary ID.
- Let the update function add
pending: trueand append or prepend the item. - Render the marker in the item component, and add
aria-busyfor accessibility. - Disable item actions that need a real server ID.
- Rely on the automatic revert to remove the flag. Never clear it by hand.
Exercise
In the complete example, a user clicks the "Delete" button on a message that is still showing "(Sending...)". Why is that a problem, and how do you prevent it using the pending flag? Also, why does the real message that arrives later not need pending set to false?
Show answer
The pending row has a temporary ID such as temp-..., which the server has never seen, so a delete request for it would target a record that does not exist. Prevent it by passing disabled={message.pending} to the delete button, so the button is inactive while the flag is true. The real message needs no pending: false because it comes from the real messages prop, which never had the field. When the Action finishes, React stops using the optimistic list and renders the real one, so message.pending is undefined (falsy) and the marker disappears without any code clearing it.
Exercise
A teammate generates the temporary ID inside the update function with crypto.randomUUID(). In development, the pending row's key seems to change between renders. What is the cause, and what is the fix?
Show answer
React can call the update function more than once for the same update, for example in Strict Mode, and the function is expected to be pure. Each call generates a different ID, so the key is unstable. Fix it by creating the item, including its ID, in the form action and passing the whole item to the setter. The update function then only spreads the item and adds pending: true.