Sub topic 4
Deriving optimistic state with an update function
This chapter assumes you know React function components, useState, props, and async/await. It also assumes you have seen useOptimistic called with one argument. Here you will learn the second argument: the update function.
Why the second argument exists
useOptimistic(state) returns a pair. The first item is the optimistic value. The second item is a setter. With only one argument, whatever you pass to the setter replaces the optimistic value. That works for a single value such as a liked flag.
It works poorly for a list. If you want to add one message to a list, you would have to build the whole new array at every call site. The update function moves that logic into the hook call:
const [optimisticState, addOptimistic] = useOptimistic(
state,
(currentState, optimisticValue) => newState
);The update function takes two arguments:
currentStateis the state React is working from. Without other pending updates, this is the realstateyou passed in.optimisticValueis whatever you passed to the setter.
It returns the optimistic state to show. This function works like a reducer, and it must be pure. It must not mutate currentState, call the server, or read the clock. React may call it more than once.
A worked example
This thread adds a pending message while the server call runs:
import { useOptimistic } from "react";
function Thread({ messages, sendMessage }) {
const [optimisticMessages, addOptimisticMessage] = useOptimistic(
messages,
(currentMessages, text) => [
...currentMessages,
{ id: crypto.randomUUID(), text, sending: true },
]
);
async function formAction(formData) {
addOptimisticMessage(formData.get("message"));
await sendMessage(formData);
}
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>
</>
);
}Follow one submission through the code:
- The user submits the form. React runs
formActionas an Action. addOptimisticMessage("hello")calls the update function with the currentmessagesand"hello".- The function returns a new array. It copies the old messages and appends an object with
sending: true. - React renders with
optimisticMessages, so "hello" appears at once with a "Sending..." label. await sendMessage(formData)runs. The parent updates itsmessagesprop when the server responds.- When the Action finishes, React drops the optimistic layer and renders from the real
messages.
Design rules for the update function
Keep the function small and predictable.
- Return a new value. Use spread syntax,
map, orfilter. Do not callpushoncurrentState. - Pass only what you need. The second argument can be a string, a number, or an object. An object is useful when the update needs several fields.
- Mark the optimistic item. The
sending: trueflag lets the UI tell guesses from confirmed data. The flag exists only in the optimistic layer. The real list from the server will not have it. - Avoid side effects. Generate IDs outside the function if you need them to be stable. In the example,
crypto.randomUUID()runs inside the function, so a re-run can produce a different ID. A later chapter covers temporary IDs and keys in detail.
Updates other than appending
The update function can express any change, not only adding to a list. Here is one that marks a todo as done:
const [optimisticTodos, setOptimisticTodo] = useOptimistic(
todos,
(currentTodos, doneId) =>
currentTodos.map((t) => (t.id === doneId ? { ...t, done: true } : t))
);Calling setOptimisticTodo(7) shows todo 7 as done. The real todos array stays unchanged until the parent replaces it.
Common errors
| Mistake | Effect | Fix |
|---|---|---|
| Mutating `currentState` in the update function | Stale or inconsistent renders, because React may re-run the function | Return a new array or object |
| Calling the setter outside an Action or transition | React warns, and the optimistic value may not behave as expected | Call it inside a form action or `startTransition` |
| Expecting the setter to change the real state | The value disappears when the Action ends | Update the real state through the parent after the server call |
| Fetching data inside the update function | Repeated requests and unpredictable results | Do the request in the Action, after calling the setter |
Exercise
Write a useOptimistic call for a cart array of { id, name, qty } items. The setter should receive a product ID and optimistically increase that item's qty by 1. Why must the update function use map instead of changing the item directly?
Show answer
const [optimisticCart, bumpQty] = useOptimistic(cart, (currentCart, productId) => currentCart.map((item) => item.id === productId ? { ...item, qty: item.qty + 1 } : item)); The update function must be pure and must not change currentCart. map with a copied item returns a new array and leaves the real cart untouched, so React can safely re-run the function and can discard the optimistic layer cleanly when the Action ends.