React / 90
useOptimistic: instant UI that rolls back
Show the result of an action before the server confirms it. If the action fails, React drops the guess and shows the real state again, with no undo code.
A temporary copy of your state
const [optimisticValue, setOptimistic] = useOptimistic(value, reducer);value: your real state (fromuseState, props oruseActionState).reducer(current, input)(optional): how a guess changes the value, like(likes, amount) => likes + amount. Without it, whatever you pass tosetOptimisticbecomes the value.optimisticValue: equalsvaluewhenever no Action is running. While one is, it's the guessed version.
server says OK
before
click
saved
server fails
before
click
rolled back
Highlighted = the optimistic guess, shown instantly while the request is in flight.
A like button
import { startTransition, useOptimistic, useState } from "react";
import { saveLike } from "./api.js";
export default function LikeButton({ initialLikes }) {
const [likes, setLikes] = useState(initialLikes);
const [optimisticLikes, addLike] = useOptimistic(likes, (current, amount) => current + amount);
const [error, setError] = useState(null);
function handleLike() {
setError(null);
startTransition(async () => {
addLike(1); // shows instantly
try {
const saved = await saveLike(); // the server's real count
startTransition(() => setLikes(saved)); // ink it in
} catch {
startTransition(() => setError("Couldn't like. Try again."));
}
});
}
return (
<>
<button onClick={handleLike}>♥ {optimisticLikes}</button>
{error && <p role="alert">{error}</p>}
</>
);
}Render optimisticLikes, never likes, in the UI. On success, the real state and the optimistic value meet in the same render, so there's no flicker. On failure, nothing touched likes, so the count drops back on its own. You only add the error message.
An optimistic like
Try iton screen (optimistic)
real state (post)
A chat message that says "Sending…"
Inside a form action you're already in an Action, so there's no startTransition around the optimistic call. The reducer adds a temporary message marked sending:
const [optimisticMessages, addOptimistic] = useOptimistic(
messages,
(current, text) => [...current, { id: crypto.randomUUID(), text, sending: true }]
);
async function sendAction(formData) {
const text = formData.get("message");
addOptimistic(text);
const saved = await sendMessage(text);
startTransition(() => setMessages((m) => [...m, saved]));
}
return (
<>
{optimisticMessages.map((m) => (
<p key={m.id}>{m.text} {m.sending && <small>Sending…</small>}</p>
))}
<form action={sendAction}>
<input name="message" />
</form>
</>
);Gotchas
Recall
Can you answer these?
0/4
Answer out loud (or in your head) before you tap. That's what makes it stick.
Saved on this device only. No login.
