React 19's
useOptimistic, live. Send a message and it appears instantly (pending) before the server confirms, then reconciles into the real state — or rolls back automatically if the request fails. No manual revert code.
▶ Live demo · How it works · Run locally
"Optimistic UI" — update the screen before the server responds so the app feels instant — used to mean hand-rolling temporary state and manual rollback on error. React 19's useOptimistic builds it into the framework. This shows both the instant update and the automatic revert, side by side with the code.
const [optimistic, addOptimistic] = useOptimistic(
messages, // the real, committed state
(cur, text) => [...cur, { text, status: "sending" }] // how to show a pending change
);
startTransition(async () => {
addOptimistic(text); // 1. render the bubble instantly (from optimistic state)
const saved = await save(text); // 2. the real request
setMessages(m => [...m, saved]); // 3. commit → optimistic reconciles into real
// on throw: no commit → React discards the optimistic value and snaps back
});- Instant:
addOptimisticderives a temporary state that renders immediately — no network wait. - Reconcile: when the action commits the real state (
setMessages), the optimistic entry is replaced by the confirmed one ("sending…" → "✓ sent"). - Auto-rollback: if the async action inside
startTransitionfinishes without committing (an error), React throws away the optimistic value and the UI returns to the real state — the failed bubble just disappears. Flip "next send fails" in the demo to watch it.
The key mental model: the revert is driven by whether the underlying state actually changed, not by any rollback code you write.
npm install
npm run dev
npm run builduseOptimistic must be updated inside a transition or a form action (so React knows when the "optimistic window" ends). The demo uses startTransition with an async function; with a <form action> it's even terser.
Ideas: a <form action> + useActionState version, optimistic like/counter, per-item retry, list reordering. PRs welcome.
If this made optimistic UI click, a ⭐ helps others find it.
MIT © dev48v