Sub topic 3
The useOptimistic hook: state in, optimistic state out
This chapter assumes you know useState, props and lifting state up, and async/await. It also assumes you have sent data to a server with fetch or a server function. Here you learn the hook's shape and the simplest way to use it. Later chapters cover the update function and failure handling.
The signature
useOptimistic takes the real state and returns a value to render, plus a function to change that value temporarily.
const [optimisticState, setOptimistic] = useOptimistic(state);stateis the real value. It usually comes from props or from auseStatein a parent. The hook does not own it.optimisticStateis what you render. When nothing is pending, it equalsstate. While an Action is running, it can hold a temporary value.setOptimisticsets the temporary value. Each call asks React to render with the value you pass, until the Action finishes.
The hook has no setter for the real state. The real state still changes through your normal useState setter, or through new props after the server confirms the change.
A worked example: a like button
A like button is the smallest useful case. The parent holds the real liked value and a function that saves it. The button renders the optimistic value, so the label flips on click instead of after the server responds.
import { startTransition, useOptimistic, useState } from "react";
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) {
// Stand-in for a real request.
await new Promise((resolve) => setTimeout(resolve, 1000));
startTransition(() => setLiked(next));
}
return <LikeButton liked={liked} saveLiked={saveLiked} />;
}Click the button. The label changes at once, and one second later the real state catches up. Both values are now the same, so nothing visibly changes.
Why the setter lives inside startTransition
React treats the optimistic value as belonging to an Action. An Action is a function you run inside a transition, such as the async function passed to startTransition. The optimistic value lasts as long as that Action is pending.
Here is the order of events in handleClick:
startTransitionstarts an Action and marks it pending.setOptimisticLiked(!liked)makesoptimisticLikedshow the new value right away.await saveLiked(!liked)runs. The optimistic value stays in place.- When the Action finishes, React stops using the optimistic value and renders
likedagain.
Step 4 is why the parent must update the real state before the Action ends. Otherwise the button would briefly show the old value. The next chapters cover this reversion in detail.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Calling `setOptimisticLiked` in a plain click handler | React logs a warning, and the optimistic value does not behave as expected | Wrap the work in `startTransition(async () => { ... })` |
| Never updating the real state | The UI jumps back to the old value when the Action ends | Update the parent state, or refetch, before the Action finishes |
| Reading `optimisticLiked` to decide what to send | A repeated click can send a value based on temporary state | Compute what to send from real state, as `!liked` does above |
| Storing the optimistic value in `useState` | It never reverts, and you lose the hook's main benefit | Render the value the hook returns |
What passing a value does
With no update function, the value you pass to the setter replaces the optimistic state outright. That works well for a boolean, a string, or any value you can compute completely before you call the setter. For lists, where you want to add one item to the current list, use the update function. The next chapter covers it.
Exercise
In the like button above, what does optimisticLiked equal while no Action is running, and what is the setter's role during an Action?
Show answer
While no Action is running, optimisticLiked equals the real liked prop. During an Action, calling setOptimisticLiked makes optimisticLiked show the value you passed, and it stays that way until the Action finishes. Then React renders the real liked value again.
Exercise
A teammate calls setOptimisticLiked(!liked) in a regular onClick handler without startTransition. Why is this a problem, and how do you fix it?
Show answer
The setter is meant to run inside an Action, which gives the optimistic value a pending operation to last for. Outside one, React warns and the value has no clear lifetime. Wrap the setter call and the await in startTransition(async () => { ... }).