Optimistic Updates with useOptimistic
Build, explain and debug React 19 interfaces: components, rendering, state, effects, identity, forms and actions, server components, concurrency, performance and testing, ending with architecture and typing work on real component challenges.
What you will be able to do
#- Layer a temporary optimistic value over authoritative state.
- Drive optimistic updates from inside an action or transition.
- Explain why a failed action reverts the optimistic value.
Overview
#Show the result before it is confirmed
An optimistic update renders the expected result immediately, while the real request is still in flight. If the request fails, React discards the optimistic value and falls back to the real state. React 19 provides useOptimistic for this.
const [optimisticLikes, addOptimisticLike] = useOptimistic(
likes,
(current, increment: number) => current + increment,
);
The first argument is the real state. The optional reducer combines it with the value you pass to the setter. The returned state is the optimistic view.
Optimistic updates run inside actions
The optimistic setter only has an effect while an action or transition is pending. Calling it outside that window does nothing useful. The typical shape is an action that sets the optimistic value, awaits the request, then returns, at which point the real state takes over.
async function action(formData: FormData) {
addOptimisticMessage(String(formData.get('text') ?? ''));
await sendMessage(formData);
}
Reverting on failure
The optimistic value is temporary. When the action finishes, React re-renders with the real state. If the request failed and the real state was not updated, the optimistic value disappears, which is the revert. Do not store the optimistic value yourself.
Pitfall: optimistic state must derive from base state
useOptimistic must be given the authoritative state as its first argument, and the optimistic value must be a pure function of that state. If you pass a copy you manage separately, the revert will not work and the UI can drift.
Pitfall: not for irreversible actions
Only use optimistic updates when a failure is acceptable and reversible in the UI. For payments or destructive actions, wait for confirmation.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
The send request fails. What does the message list show after the action settles?
Read the code, then choose the best answer. The reference explanation stays hidden until you respond. stimulus.tsxconst [optimistic, addOptimistic] = useOptimistic(messages, (cur, m) => [...cur, m]); async function action(formData: FormData) { addOptimistic({ id: 'temp', text: String(formData.get('text')) }); await send(formData); // rejects }Exercise 2Implement
Add an optimistic like button that increments the count immediately and reverts if the request fails.
starter.tsxfunction LikeButton({ postId, likes }: { postId: string; likes: number }) { return <button>{likes}</button>; }Reveal the reference answer
reference.tsximport { useOptimistic, useTransition } from 'react'; function LikeButton({ postId, likes }: { postId: string; likes: number }) { const [optimisticLikes, addOptimistic] = useOptimistic(likes, (cur, n: number) => cur + n); const [isPending, startTransition] = useTransition(); return ( <button disabled={isPending} onClick={() => startTransition(async () => { addOptimistic(1); await likePost(postId); })} > {optimisticLikes} </button> ); }Authored expected output: The count increases immediately on click and reverts if likePost rejects.
The optimistic value is derived from the real likes count through the reducer. The transition keeps the update pending until the request settles, at which point the real count is shown.
Exercise 3Debug
This optimistic count never reverts on failure. Explain why.
starter.tsxconst [optimistic, setOptimistic] = useState(0); async function onClick() { setOptimistic(optimistic + 1); await like(); }Reveal the reference answer
reference.tsxconst [optimistic, addOptimistic] = useOptimistic(likes, (cur, n: number) => cur + n); async function onClick() { startTransition(async () => { addOptimistic(1); await like(); }); }Authored expected output: After the fix, a failed like reverts to the real count.
The original uses useState, which holds a permanent value that is never discarded. useOptimistic layers a temporary value over authoritative state and reverts to it when the action settles.
Exercise 4Interview
Explain when you would and would not use an optimistic update, with an example of each.
starter.tsx// likes, comments, payments, deletesReveal the reference answer
reference.tsxUse optimistic updates when the action usually succeeds, the result is easy to predict, and a failure can be cleanly undone in the UI, such as liking a post or posting a comment. Do not use them for irreversible or high-stakes actions such as payments, account deletion or anything with a confirmation step, because showing success before it is confirmed misleads the user. For those, show a pending state and wait for the result.Authored expected output: A rule based on reversibility and stakes, with one good and one bad example.
The decision hinges on whether a wrong guess is cheap to undo. Reversible, low-stakes actions are good candidates; irreversible ones are not.
Common misconceptions
#- useOptimistic persists the value. It is temporary and reverts to the real state when the action settles.
- You can call the optimistic setter anywhere. It only applies during a pending action or transition.
- The optimistic value replaces the real state. It is layered on top of the real state and discarded on completion.
- Optimistic updates are safe for any mutation. Use them only when a failed update can be undone in the UI.
Follow-up practice
#- react-actions-and-server-functions
- react-suspense-boundaries
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.