Sub topic 10
Temporary IDs and stable keys
This chapter assumes you know how useOptimistic and the update function work, how a form action runs inside a transition, and how React uses key to match list items between renders. You should also be comfortable with async/await.
The previous chapters built an optimistic message list. This chapter covers one detail that decides whether the list feels smooth or glitchy: which key each message gets, and whether that key survives the move from "sending" to "saved".
Why keys matter more with optimistic items
React uses the key of each list item to decide whether an item is the same one as in the last render. Two renders with the same key mean "update this item". A key that disappears and a new key that appears mean "destroy the old item and create a new one".
An optimistic message has a problem that ordinary list items do not have. You show it before the server has created a record, so it has no server ID. You still have to give it some key. Later the real message arrives with a server-assigned ID, and the optimistic copy is dropped from the list. If the two copies have different keys, React sees a removal and an insertion, not an update.
Replacing an item instead of updating it has visible costs:
- The DOM node is unmounted and a new one is mounted, which can cause a flicker.
- CSS transitions and entry animations run again, so the message appears to "pop in" twice.
- State inside the item component is lost, for example an expanded panel, a half-typed edit, or a hover state.
- Focus moves away if the user had focused something inside that item.
The goal is that the key of an item is the same before and after the server confirms it.
Where not to get the key
Three common choices cause trouble.
The array index. The optimistic item is appended at the end, so its index is correct while pending. But if the real list is reordered, or another user's message arrives first, indexes shift and React reuses the wrong DOM nodes for the wrong messages. Index keys are only safe for lists that never reorder or insert in the middle, and a shared message thread does not meet that condition.
Math.random() or crypto.randomUUID() during render. A key generated in the JSX changes on every render, so every item remounts every time the component renders. This is never correct.
A random ID created inside the update function. This one looks fine and appears in many examples:
const [optimisticMessages, addOptimisticMessage] = useOptimistic(
messages,
(current, text) => [
...current,
{ id: crypto.randomUUID(), text, sending: true }, // problem
]
);The problem is that React can call the update function more than once for the same update. It replays pending updates when the real state changes while the Action is still running, it may re-run it on re-renders, and in development Strict Mode calls it twice to check that it is pure. Each call produces a different UUID, so the optimistic item can get a new key every time the list is recomputed.
Generate the ID before the optimistic update
Create the ID in the event handler or form action, which runs once per submission. Pass it into the optimistic setter and also send it to the server. The update function then only copies data, so it returns the same result every time it is called.
import { useOptimistic } from "react";
function Thread({ messages, sendMessage }) {
const [optimisticMessages, addOptimisticMessage] = useOptimistic(
messages,
(current, newMessage) => {
// Defensive: skip the item if the real list already contains it.
if (current.some((m) => m.clientId === newMessage.clientId)) {
return current;
}
return [...current, newMessage];
}
);
async function formAction(formData) {
const message = {
clientId: crypto.randomUUID(),
text: formData.get("message"),
sending: true,
};
addOptimisticMessage(message);
await sendMessage(message);
}
return (
<>
<ul>
{optimisticMessages.map((m) => (
<li key={m.clientId}>
{m.text}
{m.sending && <small> (Sending...)</small>}
</li>
))}
</ul>
<form action={formAction}>
<input type="text" name="message" />
<button type="submit">Send</button>
</form>
</>
);
}Two details matter here. The clientId is created once in formAction, so it is stable for the life of that message. The key uses clientId, not the server id, so it does not depend on anything the server has not yet assigned.
Carry the client ID through the server
The key only stays stable if the real message in messages has the same clientId. That means the server has to store the client ID, or at least echo it back in its response. Here is a parent that does this with a fake server:
import { startTransition, useState } from "react";
function fakeServerSave(message) {
return new Promise((resolve) => {
setTimeout(() => {
resolve({
id: Math.floor(Math.random() * 1_000_000), // server-assigned ID
clientId: message.clientId, // echoed back
text: message.text,
});
}, 1000);
});
}
export default function App() {
const [messages, setMessages] = useState([
{ id: 1, clientId: "seed-1", text: "Hello" },
]);
async function sendMessage(message) {
const saved = await fakeServerSave(message);
startTransition(() => {
setMessages((current) => [...current, saved]);
});
}
return <Thread messages={messages} sendMessage={sendMessage} />;
}The saved message has no sending field, so the "(Sending...)" label disappears. It has the same clientId, so the <li> is updated in place. The server id is still available for later work, such as deleting the message.
Wrapping setMessages in startTransition is needed because a state update after an await is no longer inside the Action's transition. Without it, React can render the real list while the optimistic value is still active. The some check in the update function protects against that overlap. Without the check, you could see the same message twice for a moment and get a duplicate key warning.
Comparing key strategies
| Strategy | Stable while pending | Stable after confirmation | Main problem |
|---|---|---|---|
| Array index | Yes, until the list reorders | No, if the list changes | Wrong nodes reused after inserts or reordering |
| Random value in render | No | No | Every item remounts on every render |
| Random value in update function | Not guaranteed | No | Update function is impure and can be replayed |
| Temp ID, replaced by server ID | Yes | No | Remount when the real item arrives |
| Client ID generated once and saved by the server | Yes | Yes | The server must store or echo the ID |
If the server cannot store a client ID, you have a fallback. Keep the temp ID as a separate field on the optimistic item, and when the real item arrives, map it back to the same key on the client. This means keeping a lookup from server id to clientId in state. That is extra bookkeeping, so prefer the server echoing the ID when you control the API.
Trusting the client ID on the server
A client-generated ID is also useful for the request itself. If the user double-clicks or the network retries the request, the server can use the clientId as an idempotency key and ignore a duplicate instead of creating two messages.
Still, the ID comes from the client, so the server should not blindly use it as the primary key. A reasonable approach:
- Validate that it has the expected format, for example a UUID.
- Scope uniqueness to the user or thread, so one user cannot collide with or overwrite another user's record.
- Keep your own server
idas the primary key, and storeclientIdin a separate column.
Environment gotchas
crypto.randomUUID() is only available in secure contexts, which means HTTPS or localhost. On a plain HTTP page served from another host it is undefined, and calling it throws. It is also missing in very old browsers. If you need a fallback for keys only, a counter held in a ref works, because keys only need to be unique within one list on one page:
import { useRef } from "react";
function useTempId() {
const counter = useRef(0);
return () => `tmp-${++counter.current}`;
}This is not safe as a server idempotency key, because two tabs can generate the same tmp-1. Use it for list keys only.
Keep the ID in the data, not computed from it. Deriving a key from the message text, such as key={m.text}, breaks when the user sends the same text twice, which produces duplicate keys in the same list.
Checklist
- Generate the ID once per submission, in the event handler or form action.
- Pass the ID into the optimistic setter as part of the update value.
- Keep the update function pure, with no random or time-based calls.
- Send the ID to the server and have it echoed back on the saved record.
- Use that ID as the
key, not the index and not the serveridalone. - Guard against the item appearing twice if real state arrives early.
Exercise
A teammate writes the update function as (current, text) => [...current, { id: crypto.randomUUID(), text, sending: true }] and uses key={m.id}. In development, the pending message's input focus and CSS fade-in restart whenever another message arrives from the server during the send. Explain the cause and give the fix.
Show answer
The update function is impure. React replays pending optimistic updates when the real state (messages) changes during the Action, so the function runs again and produces a new UUID. The key changes, so React unmounts and remounts the pending item, which restarts its animation and drops focus. The fix is to generate the ID once in the form action (const clientId = crypto.randomUUID()), pass { clientId, text, sending: true } to addOptimisticMessage, make the update function only copy that value into the list, and use key={m.clientId}.
Exercise
Your server returns a saved message as { id: 482, text: "Hi" } and does not return the client ID. The optimistic item used key={m.clientId}. What happens when the saved message arrives, and what are two ways to fix it?
Show answer
The saved message has no clientId, so its key is undefined or a different value from the optimistic item's key. React unmounts the optimistic <li> and mounts a new one, causing a flicker and losing any local state. Fix 1: change the server to store or echo the clientId so the saved record keeps the same key. Fix 2: keep a client-side map from server id to clientId when the response arrives, and use the mapped value as the key for that item.