Sub topic 10
Temporary IDs and stable keys
This chapter assumes you know how to build a list in React and why key matters. It also assumes you have built the optimistic message list from the earlier chapters. Here you will fix a detail that code like that often gets wrong: where an optimistic item's key comes from.
Why an optimistic item needs a key
An optimistic message exists only on the client. The server has not saved it, so it has no database ID yet. React still needs a key so it can tell list items apart between renders.
A key is stable when the same logical item keeps the same key on every render. If the key changes, React discards the old DOM node and builds a new one. In a message list this can cause three visible problems:
- A fade-in animation plays again.
- Focus or text selection inside the item is lost.
- Local state inside the item component is reset.
The first obvious choice is the array index, but an index shifts when items are inserted or removed. A random ID is better, as long as you create it in the right place.
Where to generate the ID
The update function passed to useOptimistic should be pure. React can call it again each time it recomputes the optimistic state. This happens whenever the real state changes or the component re-renders while an Action is pending. Strict Mode also calls it twice in development.
Suppose the update function calls crypto.randomUUID(). Each call can produce a different ID for the same pending message, so the key changes and the item remounts.
Generate the ID in the action
The version below creates the ID in the form action. It passes the same ID to the optimistic update and to the server.
import { useOptimistic, useState } from "react";
async function postMessage(message) {
const res = await fetch("/api/messages", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(message),
});
if (!res.ok) throw new Error("Request failed");
return res.json();
}
function Thread({ messages, sendMessage }) {
const [optimisticMessages, addOptimisticMessage] = useOptimistic(
messages,
(current, message) => [...current, { ...message, sending: true }]
);
async function formAction(formData) {
const message = {
id: crypto.randomUUID(),
text: formData.get("message"),
};
addOptimisticMessage(message);
await sendMessage(message);
}
return (
<>
<ul>
{optimisticMessages.map((m) => (
<li key={m.id}>
{m.text}
{m.sending && <small> (Sending...)</small>}
</li>
))}
</ul>
<form action={formAction}>
<input type="text" name="message" />
<button type="submit">Send</button>
</form>
</>
);
}
export default function App() {
const [messages, setMessages] = useState([]);
async function sendMessage(message) {
const saved = await postMessage(message);
setMessages((current) => [...current, saved]);
}
return <Thread messages={messages} sendMessage={sendMessage} />;
}The example assumes the server stores the id it receives and returns the saved message with that same id. crypto.randomUUID() is only available in secure contexts, meaning HTTPS or localhost.
What happens when the real item arrives
When the Action finishes, React drops the optimistic value and renders from the real messages prop. The real list now contains the saved message. The sequence is shown below.
Because the key a1 is the same before and after, React keeps the existing <li> and only removes the "Sending..." label.
When the server assigns the ID
Sometimes the server must choose the ID, for example with an auto-increment column. The saved item then has a different ID from the temporary one. If you use m.id as the key, the key changes, and the item remounts at the moment it is confirmed.
You have two options:
| Approach | How it works | Trade-off |
|---|---|---|
| Client-generated ID sent to the server | Server stores the client's UUID as the ID. | Needs server support. The server must validate the ID. |
| Separate `clientKey` field | Each item carries `clientKey`. The server echoes it back. The list uses `key={m.clientKey}`. | Needs an extra field on the server response. |
A client-generated ID also lets the server detect a retried request with the same ID and ignore the duplicate.
Summary of rules
- Create temporary IDs in the event handler or Action, not in the update function.
- Pass the same ID to the optimistic update and to the server.
- Keep the key the same from pending state to saved state whenever you can.
- Never use the array index as the key for a list that grows optimistically.
Exercise
A teammate writes the update function as (current, text) => [...current, { id: crypto.randomUUID(), text, sending: true }]. The pending message flickers and loses focus on its inner input whenever the parent re-renders. What is the likely cause, and how do you fix it?
Show answer
The update function runs again on each recompute, so every run creates a new random ID. The key changes, and React remounts the item. Fix it by creating the ID once in the form action, passing { id, text } to addOptimisticMessage, and having the update function only spread it into the list with sending: true. Then send the same ID to the server so the saved item keeps the same key.