Sub topic 1
What an Optimistic Update Is and Why It Helps
Most interfaces that save data follow the same loop. The user acts, the app sends a request, the app waits, and then the screen changes. An optimistic update changes the order. The app changes the screen first, as if the request had already succeeded, and then sends the request. If the server agrees, nothing more happens. If the server refuses, the app undoes the change and tells the user.
This chapter explains the idea and the trade-off it makes. It also shows why the manual version of the pattern is easy to get wrong. The later chapters introduce React's useOptimistic hook, which handles those problems for you.
Prerequisites
This chapter assumes you already know the following:
- React function components and the
useStatehook. - Passing props and lifting state up to a parent component.
- Basic
async/awaitand Promises in JavaScript, includingtry/catcharound an awaited call. - How an app submits data to a server, either with
fetchor with a server function.
You do not need any React 19 features yet. The examples in this chapter use only useState.
The Problem: Waiting for the Server
A network round trip takes time. On a fast connection it may be 50 to 150 milliseconds. On a slow mobile connection, or when the server does real work, it can reach several seconds. During that time the interface has two honest choices:
- Show the old data and do nothing visible.
- Show a spinner or a disabled control.
Both make the app feel slow, even when the server is working correctly. A user who taps "Like" and sees nothing for 800 milliseconds may tap again, which can cause duplicate requests or flip the like back off.
Here is the standard approach, sometimes called a pessimistic update. The component changes its state only after the server confirms:
import { useState } from "react";
export function LikeButtonPessimistic({ initialLiked, saveLiked }) {
const [liked, setLiked] = useState(initialLiked);
const [saving, setSaving] = useState(false);
async function handleClick() {
setSaving(true);
try {
await saveLiked(!liked);
setLiked(!liked);
} finally {
setSaving(false);
}
}
return (
<button onClick={handleClick} disabled={saving}>
{liked ? "Unlike" : "Like"}
</button>
);
}This code is correct and easy to reason about. The screen never shows anything the server has not confirmed. The cost is that the label stays the same until saveLiked resolves.
The Optimistic Idea
An optimistic update bets that the request will succeed. Most requests do succeed, so the bet usually pays off. The app shows the expected result immediately and treats the server response as a confirmation, not as the trigger for the visible change.
The sequence of events looks like this:
Three parts make up the pattern:
- Predict. The app computes what the data will look like if the request succeeds.
- Show. The app renders that prediction right away.
- Reconcile. When the server replies, the app either keeps the prediction, replaces it with the server's version of the data, or rolls back.
The word "optimistic" refers to step 1. The app assumes success.
What You Gain
The main benefit is perceived speed. The actual request takes the same time as before. What changes is the delay between the user's action and visible feedback, which drops to the time of one render.
Other benefits follow from that:
- The interface feels direct. A message appears in the chat as soon as the user sends it. A task moves to "done" as soon as it is checked.
- Fewer abandoned or repeated actions. Users who see an immediate result are less likely to click again.
- Slow networks hurt less. The server's delay is hidden for the common case, which is success.
This matters most for small, frequent actions: likes, toggles, reordering, adding to a list, and sending a message.
What It Costs
The pattern has a price, and you should name it before you choose it. For a short time the screen can show something that is not true. The user sees "liked" while the server has not yet recorded the like. If the request fails, the screen was wrong, and the app must correct it.
That leads to four costs:
- Rollback logic. You need a path that restores the earlier state when the request fails.
- A visible correction. A change that disappears is confusing unless you explain it. You usually need an error message.
- Prediction code. You must write code that guesses the server's result, and the guess can differ from the real result. For example, the server may assign an ID, a timestamp, or a normalized value that the client does not know.
- More states to test. Every action now has a success path, a failure path, and a period in between.
The trade-off is a lower perceived delay in exchange for a brief risk of showing wrong information. You accept the risk only when the prediction is very likely to be right and a rollback is harmless.
A Hand-Rolled Optimistic Update
To see what the pattern involves, here is the same like button written optimistically with only useState:
import { useState } from "react";
export function LikeButtonOptimistic({ initialLiked, saveLiked }) {
const [liked, setLiked] = useState(initialLiked);
const [error, setError] = useState(null);
async function handleClick() {
const previous = liked;
const next = !previous;
setError(null);
setLiked(next); // show the expected result now
try {
await saveLiked(next);
} catch {
setLiked(previous); // roll back
setError("Could not save your like. Please try again.");
}
}
return (
<>
<button onClick={handleClick}>{liked ? "Unlike" : "Like"}</button>
{error && <p role="alert">{error}</p>}
</>
);
}Compare this with the pessimistic version. The label changes on the click, not after the network call. The component also has to remember previous and restore it in the catch block.
You can try both versions with a fake server function that waits and sometimes fails:
function fakeSave(value) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (Math.random() < 0.3) reject(new Error("Network error"));
else resolve(value);
}, 1000);
});
}Pass fakeSave as the saveLiked prop. In the pessimistic button, the label stays the same for one second after each click. In the optimistic button, the label changes at once. About one click in three, it flips back after a second and an error appears.
Where Manual Optimism Breaks
The small example above hides several problems. They appear as soon as the component does more than toggle one boolean.
Overlapping requests
Suppose the user clicks twice quickly. The first click saves true, and the second saves false. If the second request finishes first and the first request then fails, the rollback restores previous from the first click. That sets the screen to a value that no longer matches what the user last asked for. The previous variable is a snapshot from one click, and it goes stale when other clicks happen in between.
Rollback to the wrong value
Rollback by saving a snapshot works only when nothing else changes the state during the request. In a list, other items may be added, removed, or updated by other requests or by new data from the server. Restoring a whole saved list would erase those changes.
Mixing guesses with confirmed data
When you write the prediction into your real state, you lose the difference between "confirmed" and "guessed". After a failure, you have to find and remove the guessed entry by hand. If the app reloads real data in the meantime, the guess can appear twice or overwrite fresh data.
Cleanup after unmount
If the user leaves the page while the request is running, the catch block may call setLiked on a component that no longer exists. In current React versions this does not crash, but it shows that the lifecycle of the request is separate from the lifecycle of the component, and you are responsible for both.
These problems come from one design choice. A hand-rolled update stores the guess in the same state as the truth. React's useOptimistic hook takes a different approach. It keeps the real state as the source of truth, and it shows an optimistic copy only while an asynchronous action is running. When the action ends, React drops the copy and shows the real state again. The next chapters build up to this, starting with Actions and transitions.
Choosing Where to Be Optimistic
Not every action suits the pattern. Use these questions to decide:
| Question | Good fit | Poor fit |
|---|---|---|
| How often does the request succeed? | Almost always, such as a like or a chat message | Often fails, such as a coupon code check |
| Can the client predict the result? | Yes, because the result is the input plus a flag | No, because the server computes the result |
| Is a rollback harmless? | Yes, because the user can retry | No, because money moves or an email is sent |
| Is the user waiting on the result to continue? | No, because they can keep working | Yes, because the next step needs real data |
The last chapter of this tutorial covers the poor-fit cases in detail. For now, remember the rule of thumb. The more reversible and predictable an action is, the better an optimistic update fits it.
Edge Cases to Keep in Mind
Even for a good fit, plan for these situations before you write code:
- Server-generated values. A new message gets its real ID from the server. Until then, the interface needs a temporary ID so that list items have stable keys. A later chapter covers this.
- Partial failure. A request can succeed on the server but fail to reach the client, for example if the connection drops after the server commits. The app then rolls back a change that actually happened. Design the server calls so that a retry is safe.
- Server-side changes to your data. The server may trim whitespace, reject a field, or apply a rule. The confirmed data can differ from the prediction. The interface should show the confirmed version once it arrives.
- Accessibility. A change that appears and then vanishes is hard to notice for screen reader users. Use a visible message with an alert role, as the example does, so the correction is announced.
- Indicating uncertainty. For anything the user may care about, such as a sent message, a small "Sending..." marker tells them the item is not confirmed yet.
Summary of the Pattern
An optimistic update shows the expected outcome of an action before the server confirms it. It lowers the delay the user feels, and it costs you a prediction step, a rollback path, and care around failures. Writing it by hand with a single piece of state works for one isolated toggle. It becomes fragile when requests overlap or when the list also holds confirmed data.
Exercise
A "Follow" button on a social profile toggles between "Follow" and "Following". The server accepts the request about 99.9% of the time, and a failed follow can simply be retried. Is an optimistic update a good fit? Name the one thing you must still build, and explain why the trade-off is acceptable here.
Show answer
Yes, it is a good fit. The result is easy to predict (the flag flips), failures are rare, and a rollback is harmless because the user can try again. You must still build the rollback path: if the request fails, the button returns to its previous label and an error message explains what happened. The trade-off is acceptable because the screen is wrong only for a short time and only in the rare failure case, and the cost of being wrong is small.
Exercise
In the hand-rolled LikeButtonOptimistic component, the user clicks "Like" and then quickly clicks "Unlike" before the first request returns. The first request fails. Explain what the catch block does to the screen and why that is a problem.
Show answer
The catch block of the first click calls setLiked(previous), where previous was captured at the first click (false). This sets the button back to "Like", even though the user's most recent intent was "Unlike" and the second request may still be running or may have succeeded. The saved previous value is a snapshot that went stale when the second click happened. The root cause is that the guess and the confirmed value share one piece of state, so a rollback by snapshot cannot tell which change it is undoing.
Exercise
A checkout page has a "Place order" button that charges a credit card. A teammate proposes showing "Order confirmed" immediately and rolling back if the charge fails. Give two reasons this is a poor fit.
Show answer
First, the result cannot be predicted by the client. The card may be declined, and the server decides the outcome, so failure is far from rare. Second, a rollback is not harmless. Telling a user their order is confirmed and then reversing it is confusing and may lead them to act on false information, such as leaving the page or expecting a delivery. Money and confirmation emails also make the action hard to reverse. The user must wait for real confirmation.