React useOptimistic Playground — Optimistic UI Example
Update a like button immediately while a simulated save is pending.
The live editor loads here with JavaScript enabled.
Run in Playground ↗The original source and explanation are available below.
Changes here stay separate from your main playground. Use Open in TryJS inside the editor to keep working with your changes.
Useful? Help keep TryJS free and independent.
Support TryJSWhat to expect
A click changes the visible like count immediately. The confirmed count updates after the delay and the Saving message disappears.
About this example
Optimistic UI shows the intended result while an action is still pending. This client-side example combines useOptimistic with a transition and a local delay. It sends no server requests and does not demonstrate server actions or persisted data.
How It Works
Apply the optimistic update
The transition starts an async action and adds a temporary like. useOptimistic renders that temporary value while the action is pending.
Commit the confirmed value
After the simulated save, the state is updated. The confirmed value becomes the basis for the next optimistic action.
Read the original source
This is the starting code. Your edits stay in the live editor above.
JSX
import { useOptimistic, useState, useTransition } from "react";
export default function App() {
const [likes, setLikes] = useState(0);
const [optimisticLikes, addOptimisticLike] = useOptimistic(likes, value => value + 1);
const [pending, startTransition] = useTransition();
const delay = 1200;
function like() {
startTransition(async () => {
addOptimisticLike();
await new Promise(resolve => setTimeout(resolve, delay));
setLikes(value => value + 1);
});
}
return <main>
<h1>Optimistic likes</h1>
<p>The screen updates before this simulated save finishes.</p>
<button onClick={like} disabled={pending}>♥ {optimisticLikes} likes</button>
<p aria-live="polite">{pending ? "Saving…" : "Saved"}</p>
<small>Confirmed likes: {likes}. No request is sent to a server.</small>
</main>;
}CSS
* { box-sizing: border-box; }
body { margin: 0; padding: 24px; background: #faf8f0; color: #222; font: 15px/1.6 system-ui, sans-serif; }
h1 { font-size: 24px; line-height: 1.2; margin: 0 0 12px; }
p { margin: 8px 0 16px; }
button, input { font: inherit; }
button { padding: 9px 16px; border: 1px solid #b9a200; border-radius: 7px; background: #f0d000; color: #222; cursor: pointer; }
button:disabled { opacity: .6; cursor: wait; }
input { max-width: 100%; padding: 9px 12px; border: 1px solid #aaa; border-radius: 7px; }
small { color: #595959; }
output { font-variant-numeric: tabular-nums; }