useOptimistic gives you a temporary value for the duration of an Action. You pass the real value (state or a prop) and get back what to display:
- No Action pending:
shownis justvalue. - Inside an Action:
setShown(guess)renders the guess immediately, even though the surrounding Transition is still running. With a reducer,setShown(payload)callsreducer(current, payload); with a function, it's an updater likesetState's. - When the Action ends: React discards the optimistic update. On success, your Action has set the real state (inside
startTransitionafter anawait), so the real value and the guess are replaced in one commit, with no flash. On failure, nothing changed the real state, so the display reverts to the old value.
There is no rollback code to write: reverting is the default, and success means the real state has caught up. You still have to tell the user it failed; catch the error and show a message, or let it reach an error boundary.
The setter must run inside an Action: in startTransition, or in a function passed to <form action>, formAction or another Action prop. Outside one, development logs an error and the value flashes and reverts.
Reducer form. For lists, useOptimistic(items, (current, text) => [...current, { text, pending: true }]) adds pending entries on top of the real list. If the real list changes while the Action is pending, React re-runs the reducer on the new list, so optimistic entries stay on top of the latest data.
It pairs with useActionState: the optimistic value hides the queue's wait, while useActionState holds the confirmed result. Server-cache libraries such as TanStack Query have their own optimistic APIs.