Sub topic 3
The useOptimistic Hook: State In, Optimistic State Out
The previous chapters introduced the optimistic UI pattern and the Actions and transitions that React 19 uses to track async work. This chapter covers the hook's inputs and outputs, and the simplest way to use it: with no update function.
This chapter assumes you know the following:
- React function components and
useState. - Passing props and lifting state up.
async/awaitin JavaScript.- How a component sends data to a server, either with
fetchor a server function.
The signature
useOptimistic takes real state and returns a version of that state that can be changed temporarily.
const [optimisticState, setOptimistic] = useOptimistic(state, updateFn);| Part | Kind | Meaning |
|---|---|---|
| `state` | Argument, required | The real value. It usually comes from a prop or from `useState` in a parent. This is the value that survives. |
| `updateFn` | Argument, optional | A function `(currentState, action) => newState` that computes the optimistic value. This chapter leaves it out. |
| `optimisticState` | Return value 1 | What you render. It equals `state` when no Action is pending. During an Action, it can differ. |
| `setOptimistic` | Return value 2 | Starts an optimistic update. Without `updateFn`, the value you pass becomes the optimistic state. |
The hook owns no lasting data. React does not store optimisticState the way it stores a useState value. React computes it during each render from two things: the state you pass in, and any optimistic updates that are still pending. When the pending work ends, only state is left.
A mental model: a temporary overlay
Think of state as a base layer and each optimistic update as a sticker placed on top of it. You see the sticker while the Action runs. When the Action finishes, React peels the sticker off. Whatever is on the base layer at that moment is what you see.
If your code updated the base layer to match the sticker, the screen looks unchanged. The sticker was removed, but the real value now says the same thing. If the request failed and the base layer never changed, the screen goes back to the old value.
Basic use without an update function
When the optimistic value is a complete replacement for the real one, you do not need updateFn. A like button is a good fit. The value is a boolean, and the new value is simply the opposite.
import { startTransition, useOptimistic, useState } from "react";
function fakeSave(liked) {
return new Promise((resolve) => setTimeout(() => resolve(liked), 1000));
}
function LikeButton({ liked, saveLiked }) {
const [optimisticLiked, setOptimisticLiked] = useOptimistic(liked);
function handleClick() {
startTransition(async () => {
setOptimisticLiked(!liked);
await saveLiked(!liked);
});
}
return (
<button onClick={handleClick}>
{optimisticLiked ? "Unlike" : "Like"}
</button>
);
}
export default function App() {
const [liked, setLiked] = useState(false);
async function saveLiked(next) {
const saved = await fakeSave(next);
startTransition(() => setLiked(saved));
}
return <LikeButton liked={liked} saveLiked={saveLiked} />;
}Here is what happens when you click the button while liked is false:
handleClickstarts an async transition. This is the Action.setOptimisticLiked(true)runs. React re-rendersLikeButtonandoptimisticLikedistrue. The label reads "Unlike" right away, even thoughlikedis stillfalse.saveLiked(true)waits one second, then updates the parent'slikedtotrue.- The async function passed to
startTransitionfinishes. React drops the optimistic update.optimisticLikednow reads fromliked, which istrue. The label stays "Unlike".
Notice that App is responsible for the real update. useOptimistic never writes to liked. If saveLiked did not call setLiked, the button would flip to "Unlike" for a second and then flip back to "Like".
The component computes !liked from the real value, not from optimisticLiked. In the no-update-function form, you decide the new value yourself, so base it on the real state to keep the intent clear. The update-function form, covered in the next chapter, passes the current optimistic value to your function instead.
Where the setter may be called
setOptimistic has to run inside an Action. An Action is one of these:
- The function passed to
startTransition(from thereactimport or fromuseTransition). - A function passed to a form's
actionprop.
React warns in development if you call the setter outside an Action. The reason is that React needs to know when the work ends so it can remove the optimistic value. An Action gives it that signal. An event handler on its own has no end point.
The setter should also run before the first await. React tracks the transition's scope synchronously, so code that runs after an await is no longer attached to it.
// Problem: the setter runs after the await.
startTransition(async () => {
await saveLiked(!liked);
setOptimisticLiked(!liked); // too late: outside the Action's scope
});
// Correct: set first, then await.
startTransition(async () => {
setOptimisticLiked(!liked);
await saveLiked(!liked);
});Even if the first version did not warn, the logic is backward. An optimistic update is useful only while the request is in flight, so it must be set before you wait for the server.
Using useTransition for a pending flag
startTransition imported from react is enough for the like button. If you also want to know whether an Action is running, for example to disable the button, use the hook form:
import { useOptimistic, useTransition } from "react";
function LikeButton({ liked, saveLiked }) {
const [isPending, startTransition] = useTransition();
const [optimisticLiked, setOptimisticLiked] = useOptimistic(liked);
function handleClick() {
startTransition(async () => {
setOptimisticLiked(!liked);
await saveLiked(!liked);
});
}
return (
<button onClick={handleClick} disabled={isPending}>
{optimisticLiked ? "Unlike" : "Like"}
</button>
);
}Disabling the button while isPending is true is a simple way to avoid overlapping requests. A later chapter covers what to do when you let them overlap.
What happens when the base state changes
Because optimisticState is computed from state on each render, a change to state during an Action affects the result.
- With no update function, the pending optimistic value takes priority over the base for as long as the Action runs. A new base is ignored until the Action ends.
- After the Action ends, the displayed value follows
state, whatever it is at that moment.
This is why the hook is safe to use with data that other sources can also change. If a real-time push updates liked while your request is in flight, the final render shows the pushed value, not a stale optimistic guess.
It also explains a common surprise. If your save function updates state to a value different from the optimistic value, say the server normalized the data, the UI shows the optimistic value first and then jumps to the server's. This is correct behavior, not a bug. The hook displays whatever the base layer holds once the Action ends.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Console warning that an optimistic update happened outside a transition or Action | The setter was called from a plain event handler, an effect, or a timer | Wrap the call in `startTransition` or move it into a form action |
| The UI flips to the new value, then flips back | Nothing updated the real `state` | Update the parent's state when the request succeeds |
| No optimistic value ever appears | The setter ran after an `await`, or the component rendered a different variable than `optimisticState` | Call the setter before awaiting, and render the first return value |
| Value jumps after the request finishes | The server returned something different from the guess | Expected. Make the guess match what the server will normally return |
| Changing `state` in the child has no lasting effect | `useOptimistic` was given a local copy that is recreated each render | Pass state that lives outside the component, such as a prop or parent state |
Choosing the no-update-function form
Use useOptimistic(state) without an update function when:
- The optimistic value replaces the whole real value, such as a boolean, a number, a selected option, or a text field's saved value.
- The new value does not depend on earlier optimistic values.
Use the update-function form when the optimistic value is built from the real state plus something new, such as appending an item to a list. The next chapter covers that form in detail.
Exercise
A component calls const [optimisticCount, setOptimisticCount] = useOptimistic(count) and then calls setOptimisticCount(count + 1) inside an onClick handler with no startTransition, then awaits a server call that updates count in the parent. What is wrong, and what is the fix?
Show answer
The setter is called outside an Action, so React warns and cannot tell when to discard the optimistic value. Wrap the body of the handler in startTransition(async () => { setOptimisticCount(count + 1); await save(); }), keeping the setter before the first await.
Exercise
In the LikeButton example, saveLiked is changed so it waits one second but never calls setLiked. What does the user see after clicking Like, and why?
Show answer
The label changes to "Unlike" immediately, then returns to "Like" after about one second. The optimistic value lasts only while the Action runs. When the Action ends, React renders the real liked prop, which was never updated and is still false.
Exercise
What are the two return values of useOptimistic(state), and which one should the component render?
Show answer
The first is optimisticState, a value computed from state plus any pending optimistic update. The second is setOptimistic, which starts an optimistic update. Render optimisticState, because it equals state when idle and shows the temporary value during an Action.