React Reference ยท Performance and Concurrency Hooks
React useOptimistic hook
Reference for React useOptimistic: show the expected result of an action immediately, then let the real state replace it when the action finishes or fails.
useOptimistic lets a component show the expected result of an action while the real work is still in progress. You give it the real state; it returns a copy that you can update instantly with a setter. When the action ends, React throws the optimistic copy away and shows the real state again. If the action failed, the screen therefore rolls back by itself.
It only works inside an action: a function passed to <form action> or to startTransition.
const [optimisticItems, addOptimisticItem] = useOptimistic(items, reducer);
Try it
Syntax
const [optimisticState, setOptimistic] = useOptimistic(state, updateFn?); // updateFn: (currentState, optimisticValue) => newState
| Name | Description |
|---|---|
state |
The real value. It is returned when no action is pending. |
updateFn |
Optional reducer. It receives the current state and the value passed to the setter and returns the optimistic state. Without it the setter's argument becomes the new optimistic state directly. |
Returns: [optimisticState, setOptimistic]. optimisticState equals state outside actions. setOptimistic(value) must be called inside an action.
Errors / edge cases: calling setOptimistic outside an action logs an error in development and the update is lost.
Usage notes
- Rolls back automatically. When the surrounding action finishes (success or error), React re-renders with the real
state. Update the real state inside the same action so the screen does not flash back. - Multiple pending updates stack. Each call runs through
updateFnagain, on top of the real state, in order. - Keep optimistic items identifiable. Mark them (a
sendingflag or temporary id) so you can style them and avoid mixing them with confirmed data. - Do not store it. The value is derived on every render; never copy it into other state.
- Show errors. Rollback is silent, so display a message when the action fails.
- Forms: pair with
useActionStatefor results and withuseFormStatusfor pending buttons. - Added in React 19.