React useOptimistic — Instant UI Feedback for Async Actions
Learn how to use useOptimistic in React 19 to show optimistic UI updates while async actions are in progress. Covers chat messages, like buttons, and automatic rollback on failure.
Detailed Explanation
Optimistic UI with useOptimistic
useOptimistic (React 19) lets you show a temporary, optimistic version of state while an async action completes. The optimistic state automatically reverts to the actual state when the action finishes.
Chat Message Example
interface Message {
text: string;
sending?: boolean;
}
function Chat({ messages }: { messages: Message[] }) {
const [optimisticMessages, addOptimistic] = useOptimistic(
messages,
(state, newMessage: string) => [
...state,
{ text: newMessage, sending: true },
]
);
async function sendMessage(formData: FormData) {
const text = formData.get("message") as string;
addOptimistic(text); // Show immediately
await submitToServer(text); // Wait for server
// When complete, optimistic state reverts to actual
}
return (
<div>
{optimisticMessages.map((msg, i) => (
<p key={i} style={{ opacity: msg.sending ? 0.6 : 1 }}>
{msg.text} {msg.sending && "(sending...)"}
</p>
))}
<form action={sendMessage}>
<input name="message" />
<button type="submit">Send</button>
</form>
</div>
);
}
Like Button Example
function LikeButton({ isLiked, onToggle }: {
isLiked: boolean;
onToggle: () => Promise<void>;
}) {
const [optimisticLiked, setOptimisticLiked] = useOptimistic(isLiked);
async function handleClick() {
setOptimisticLiked(!isLiked); // Toggle immediately
await onToggle(); // Wait for server
}
return (
<button onClick={handleClick}>
{optimisticLiked ? "Unlike" : "Like"}
</button>
);
}
Automatic Rollback
If the async action throws an error, the optimistic state automatically reverts to the actual state. This means you get rollback behavior for free without writing error handling code for the UI state.
Requirements
- React 19 or canary channel
- Works best with React Server Actions and form actions
- The update function must be pure
Use Case
Use useOptimistic for chat applications showing sent messages instantly, social media like/favorite buttons, todo list additions, form submissions with immediate feedback, and any action where perceived responsiveness matters more than waiting for server confirmation.