Skip to content

dev48v/useoptimistic-lab

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

⚛️ useOptimistic Lab

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

License: MIT React 19 Vite TypeScript


Why

"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.

How it works

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: addOptimistic derives 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 startTransition finishes 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.

Run it locally

npm install
npm run dev
npm run build

Note

useOptimistic 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.

Contributing

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.

License

MIT © dev48v

About

React 19 useOptimistic, live: send a message that shows instantly (pending), commits on success, and auto-rolls-back on failure. Zero deps.

Topics

Resources

License

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors