Sub topic 4
Deriving optimistic state with an update function
This chapter assumes you know useState, props, async/await, and how to submit data from a React component. It also assumes you know the basic shape of useOptimistic and that its setter runs inside an Action, such as a form action or startTransition.
Why the hook takes a second argument
useOptimistic(state) with one argument works for simple cases. The value you pass to the setter replaces the optimistic state. That fits a like button, where the new value is just true or false.
Lists and records are different. When a user sends a message, the new optimistic list is the current list plus one item. If you pass the whole list to the setter, your component has to build that list, and it may build it from stale data. The update function moves that logic into the hook:
const [optimisticState, addOptimistic] = useOptimistic(state, updateFn);stateis the real state, usually a prop or a value fromuseState. React calls it the passthrough value.updateFn(currentState, optimisticValue)returns the next optimistic state.addOptimistic(optimisticValue)is the setter. The argument you pass to it becomesoptimisticValue.optimisticStateis what you render.
You describe the change ("add this message") and React applies it to whatever the current state is.
A first example
This is a complete, runnable example. App owns the real list. Thread shows the optimistic one.
import { useOptimistic, useState } from "react";
function fakeServerSave(text) {
return new Promise((resolve) =>
setTimeout(() => resolve({ id: crypto.randomUUID(), text }), 1000)
);
}
export default function App() {
const [messages, setMessages] = useState([{ id: "m0", text: "Hello" }]);
async function sendMessage(text) {
const saved = await fakeServerSave(text);
setMessages((current) => [...current, saved]);
}
return <Thread messages={messages} sendMessage={sendMessage} />;
}
function Thread({ messages, sendMessage }) {
const [optimisticMessages, addOptimisticMessage] = useOptimistic(
messages,
(currentMessages, pendingMessage) => [
...currentMessages,
pendingMessage,
]
);
async function formAction(formData) {
const text = formData.get("message");
addOptimisticMessage({ id: crypto.randomUUID(), text, sending: true });
await sendMessage(text);
}
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>
</>
);
}When the user submits, the new message appears at once with "(Sending...)". One second later setMessages updates the real list, the Action ends, and React renders the real list, which now contains the saved message.
Notice that the update function gets the whole pendingMessage object, not just the text. The ID is created in the event code and passed in. The next section explains why.
What React passes as currentState
currentState is not always the same as the prop. React computes it like this:
- Start with the latest real
state. - Apply each pending optimistic value, in the order the setter was called, using your update function.
- Render the result.
Two consequences follow.
- If the real state changes while an Action is still running, React reruns your update function against the new base. The optimistic layer is recomputed on top of fresh data. It is not frozen at the moment of the click.
- The update function can run more than once for the same optimistic value. This happens on rerenders, and in development under Strict Mode.
Keep the update function pure
Because React may call the function several times, it must be a pure function. It should depend only on its two arguments and return a new value. Three rules cover most mistakes.
| Rule | Wrong | Right |
|---|---|---|
| Do not mutate `currentState` | `current.push(item); return current;` | `return [...current, item];` |
| Do not generate random or time-based values inside it | `id: crypto.randomUUID()` in the update function | Create the ID before calling the setter and pass it in |
| Do not run side effects | Calling `fetch` or `console.log` as logic | Do the request in the Action, outside the update function |
The random ID rule is the one people miss. Look at the first version of this pattern, where the ID is created inside the update function:
(currentMessages, text) => [
...currentMessages,
{ id: crypto.randomUUID(), text, sending: true },
]It works in a simple demo. But each rerun produces a new ID for the same message. React sees a different key, unmounts the old <li>, and mounts a new one. You lose focus, animations, and any local state inside that item. Creating the ID once, in the form action, and passing it in gives every rerun the same ID. Chapter 10 returns to keys in more detail.
// Pure: same inputs always give the same output.
function appendPending(currentMessages, pendingMessage) {
return [...currentMessages, pendingMessage];
}Mutating state is worse than it looks
Suppose you write this by mistake:
useOptimistic(messages, (current, pending) => {
current.push(pending); // mutates the array
return current;
});current may be the same array as your real messages prop. You have then changed real state without going through setMessages. The optimistic item can stay in the list after the Action finishes, because it is now part of the "real" data. The automatic revert depends on the update function not touching real state.
One update function, several kinds of change
The optimistic value can be any shape. When one list supports several operations, pass an action object and switch on its type, as you would in useReducer.
import { startTransition, useOptimistic } from "react";
function todosReducer(todos, action) {
switch (action.type) {
case "add":
return [
...todos,
{ id: action.id, title: action.title, done: false, pending: true },
];
case "toggle":
return todos.map((t) =>
t.id === action.id ? { ...t, done: !t.done, pending: true } : t
);
case "remove":
return todos.filter((t) => t.id !== action.id);
default:
return todos;
}
}
export function TodoList({ todos, onAdd, onToggle, onRemove }) {
const [optimisticTodos, applyOptimistic] = useOptimistic(
todos,
todosReducer
);
function handleAdd(formData) {
const title = formData.get("title");
const id = crypto.randomUUID();
applyOptimistic({ type: "add", id, title });
return onAdd({ id, title });
}
function handleToggle(id) {
startTransition(async () => {
applyOptimistic({ type: "toggle", id });
await onToggle(id);
});
}
function handleRemove(id) {
startTransition(async () => {
applyOptimistic({ type: "remove", id });
await onRemove(id);
});
}
return (
<>
<ul>
{optimisticTodos.map((t) => (
<li key={t.id} style={{ opacity: t.pending ? 0.6 : 1 }}>
<input
type="checkbox"
checked={t.done}
onChange={() => handleToggle(t.id)}
/>
{t.title}
<button type="button" onClick={() => handleRemove(t.id)}>
Delete
</button>
</li>
))}
</ul>
<form action={handleAdd}>
<input name="title" />
<button type="submit">Add</button>
</form>
</>
);
}handleAdd is a form action. React runs form actions inside a transition, so the setter is allowed. If onAdd returns a Promise, React waits for it. The other two handlers call startTransition themselves with an async function.
The reducer has no knowledge of the network. It describes what each operation looks like before the server answers. That keeps it easy to test: you can call todosReducer directly with sample arrays.
Relative changes versus replacement
The toggle case is a relative change: "flip whatever the value is now". This is a reason to prefer the update function over computing the next value in the handler.
Compare the replacement form from the like button example:
setOptimisticLiked(!liked);Here liked is captured from the render in which the handler was created. If the user clicks twice quickly, both calls can read the same stale liked and send the same value. With an update function, each call is applied to the result of the previous one, so two toggles give the original value again, as the user expects.
Use the replacement form when the new value does not depend on the old one. Use an update function when it does.
When the update function runs, and when it does not
| Moment | What happens |
|---|---|
| Component renders with no pending Action | `optimisticState` equals `state`. The update function is not used. |
| You call the setter inside an Action | The value is queued. The next render applies your function to the real state. |
| Real `state` changes during the Action | React reruns the function on the new state. |
| The Action finishes | The queue is dropped. `optimisticState` equals the latest real `state`. |
The last row is the automatic revert. The next chapter covers it, including what the user sees when a request fails.
Common mistakes
- Calling the setter outside an Action. A plain click handler that calls
addOptimisticwithoutstartTransitiontriggers a development warning, and the optimistic value may show only briefly or not at all. Wrap it, or use a form action. - Forgetting to update the real state. The optimistic item disappears when the Action ends. If you never update
messages, the user sees the message vanish. The Action must end with the real state changed, usually through the parent. - Returning a different shape.
optimisticStatereplacesstatein your render. If real items have{ id, text }and optimistic ones have{ key, body }, your JSX must handle both. Keep shapes the same and add flags such assending. - Using the setter's argument as the entire state. With an update function, the argument is a description of the change, not the final list.
Summary of the model
You hand useOptimistic a real value and a pure function. When an Action runs, you describe a change with the setter, and React renders updateFn(realState, change). When the Action ends, React renders the real state again. Your job is to keep the function pure and keep the real state updating from the Action.
Exercise
A teammate writes this update function for a comment list: (comments, text) => [...comments, { id: Date.now(), text, sending: true }]. The comment briefly flickers and loses a focused "Reply" input inside it whenever another comment arrives from the server during the Action. What is the cause, and how do you fix it?
Show answer
The function is impure. Date.now() returns a new value each time React reruns the update function, and React reruns it when the real comments state changes during the Action. The optimistic comment therefore gets a new id, so its key changes. React unmounts and remounts the item, which causes the flicker and loses the input's focus and state. Fix it by creating the ID once in the form action or handler, for example const id = crypto.randomUUID();, and passing the whole object to the setter: addOptimistic({ id, text, sending: true }). The update function then becomes (comments, pending) => [...comments, pending], which returns the same item with the same key on every rerun.
Exercise
A like button uses useOptimistic(liked) and calls setOptimisticLiked(!liked) inside startTransition. Rewrite it with an update function so that two fast clicks flip the value twice instead of reading the same stale liked both times. What does the update function look like?
Show answer
Use const [optimisticLiked, toggleOptimisticLiked] = useOptimistic(liked, (current) => !current); and call toggleOptimisticLiked() inside the transition. The update function receives the current optimistic value and flips it. React applies the two queued toggles in order, so the displayed value goes back to the original after two clicks. The request code should still decide what to send. For example, it can send the final value after the Action settles, rather than relying on a captured liked.