Optimistic UI
Also called optimistic update or optimistic rendering
A pattern where the interface shows the result of an action right away, before the server confirms it, and rolls it back if the request fails.
import { useOptimistic, useState, useTransition } from 'react';
type Props = { postId: string; initialLiked: boolean; initialCount: number };
async function saveLike(postId: string, liked: boolean) {
const response = await fetch(`/api/posts/${postId}/like`, {
method: liked ? 'PUT' : 'DELETE'
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
}
export function LikeButton({ postId, initialLiked, initialCount }: Props) {
const [like, setLike] = useState({
liked: initialLiked,
count: initialCount
});
const [optimistic, setOptimistic] = useOptimistic(like);
const [isPending, startTransition] = useTransition();
const [failed, setFailed] = useState(false);
function toggle() {
if (isPending) return;
const next = {
liked: !like.liked,
count: like.count + (like.liked ? -1 : 1)
};
setFailed(false);
startTransition(async () => {
setOptimistic(next); // shows right away
try {
await saveLike(postId, next.liked);
startTransition(() => setLike(next));
} catch {
// `like` never changed, so the button reverts when this transition ends.
setFailed(true);
}
});
}
return (
<div className='flex items-center gap-3'>
<button
type='button'
aria-pressed={optimistic.liked}
onClick={toggle}
className='flex items-center gap-1.5 rounded-full border px-3 py-1.5 text-sm tabular-nums aria-pressed:border-rose-300 aria-pressed:text-rose-600'
>
<span aria-hidden>{optimistic.liked ? '♥' : '♡'}</span>
<span className='sr-only'>Like</span>
{optimistic.count}
</button>
{failed && (
<p role='alert' className='text-sm text-red-600'>
Couldn't save your like.
</p>
)}
</div>
);
}Make the like button optimistic: when clicked, fill the heart and increase the count immediately, then send the request. If the request fails, restore the previous state, shake the button briefly, and show a toast that says "Couldn’t save your like" with a Retry action. Ignore extra clicks while a request is in flight.
Paste into Layerwise or any AI coding tool.
What is Optimistic UI?
When you like a post, the heart fills instantly even though the request to the server takes a moment. That is optimistic UI: the app assumes the action will succeed, updates the screen at once, and sends the request in the background. If the server reports an error, the app puts things back the way they were and tells the person.
It makes apps feel instant, which matters most for small, frequent actions that almost always succeed: likes, checkboxes, renaming, reordering, adding to a cart. The alternative waits for the server before updating, which means a spinner after every click.
Skip it when failure is common or costly, such as payments, messages that can’t be recalled, or results the server decides. Always handle the rollback: restore the previous state, explain what failed, and offer a retry. In React 19, the useOptimistic hook manages the temporary state for you.
Related terms
All termsLoading state
The view a screen shows while its data is on the way, designed together with the outcomes that follow: loaded, empty, or error.
Undo
A way to reverse an action right after doing it, often a toast with an Undo button that appears after deleting or archiving something.
Perceived performance
How fast an app feels to people, which skeleton screens, instant feedback, and progressive loading can improve even when the real wait stays the same.
Toast notification
A brief message that slides into a corner of the screen to confirm an action, then disappears on its own after a few seconds.
Build it with Layerwise
Describe your app, watch it run in a live preview, and publish it with a database, storage, and sign-in built in.