Explain it simply
Explain it simply
In a social app, tapping Like turns the heart red immediately. The server has not actually said "saved" yet. The app trusts that the request will usually succeed and shows the answer in advance. This is called optimistic UI.
If the server reports a failure, the heart must go back to how it was. React 19 ships tools for this "show early, wait, then confirm or roll back" flow: Actions, useOptimistic and useActionState.
Problem → Why → Solution
The problem: a Like button that lies
The version below flips state right away and then sends the request. It feels fast, but if saveLike() fails, nothing flips the state back. The screen says "Liked" while the database has no like at all, and the user only learns the truth after a refresh.
The opposite approach is not good either. If you wait for the server before changing state, the button seems dead for a second and the user taps it again.
function LikeButton({ saveLike }) {
const [liked, setLiked] = useState(false);
async function toggle() {
setLiked(!liked); // flips immediately
await saveLike(!liked); // if this rejects, nobody flips it back
}
return <button onClick={toggle}>{liked ? 'Liked' : 'Like'}</button>;
}Why is a hand-written rollback hard?
A rollback means remembering the previous value, restoring it on every error path, and deciding which value wins when two requests overlap. useOptimistic treats the optimistic value as temporary state that exists only while the Action runs, so when the Action finishes it falls back to the confirmed state on its own.
Core concept: Actions, optimistic state and confirmed state
In React 19, an async function that runs inside a transition is called an Action. You can start one yourself with startTransition(async () => { ... }), or pass a function to <form action={fn}> and React runs it as an Action on every submit. While an Action runs, React knows it is pending. Three tools build on that fact.
| Tool | What it gives you | Use it when |
|---|---|---|
| useOptimistic(value) | A temporary value plus a setter, alive only during an Action | You want to show the result before the server answers |
| useActionState(fn, init) | [state, formAction, isPending] | Each submit produces a result or an error |
| useFormStatus() (react-dom) | The parent form's pending flag | The submit button lives in its own component |
1. Keep the confirmed state in useState
The value the server has confirmed (liked) is the source of truth. useOptimistic(liked) derives optimisticLiked from it.
2. Set the optimistic value inside the Action
Call setOptimisticLiked(next) only inside a transition or a form action. Calling it outside one makes React warn.
3. Wrap updates after await again
Once JavaScript passes an await, React can no longer tell that the update belongs to the transition. So setLiked(saved) goes into another startTransition. The React docs describe this as a current limitation.
4. When the Action ends, React reconciles
If the Action succeeds, the optimistic value now matches the new liked. If it fails, liked never changed, so optimisticLiked falls back to the old value by itself. You write no rollback code.
Which tool should you pick? If the user clicks something and expects an instant reaction, use useOptimistic. If the user submits a form and needs a result or an error message back, use useActionState. The two also combine well: a form action can call an optimistic setter before it awaits the server.
- Click sets the optimistic value
- The Action sends the request
- Success writes confirmed state
- Action ends: pencil is erased
The optimistic value is written in pencil. When the Action ends it is erased and only the confirmed state, written in ink, is shown. On failure the ink was never touched, so the old value reappears.
General pattern
const [shown, setShown] = useOptimistic(confirmed);
function handle(next) {
startTransition(async () => {
setShown(next); // visible right away
const saved = await save(next); // the real request
startTransition(() => setConfirmed(saved));
});
}
const [state, formAction, isPending] = useActionState(actionFn, initialState);
// <form action={formAction}> ... </form>The top part is the optimistic-update shape for an event such as a button click. The last line is the useActionState shape that keeps each form submission's result as state.
An optimistic Like button with rollback
This Like button handles two details that are easy to miss: the setLiked after await is wrapped in startTransition again, because code after an await is no longer part of the first transition, and a failed saveLike() shows the user a message. Assume saveLike is an async function that stores a boolean and resolves with the value the server confirmed. aria-pressed tells screen readers the toggle's current state.
import { startTransition, useOptimistic, useState } from 'react';
export default function LikeButton({ initialLiked = false, saveLike }) {
const [liked, setLiked] = useState(initialLiked);
const [optimisticLiked, setOptimisticLiked] = useOptimistic(liked);
const [error, setError] = useState('');
function toggle() {
const next = !optimisticLiked;
setError('');
startTransition(async () => {
setOptimisticLiked(next);
try {
const saved = await saveLike(next);
startTransition(() => setLiked(saved));
} catch {
setError('Could not save. Please try again.');
}
});
}
return (
<>
<button onClick={toggle} aria-pressed={optimisticLiked}>
{optimisticLiked ? 'Liked' : 'Like'}
</button>
{error && <p role="alert">{error}</p>}
</>
);
}Code breakdown
- Optimistic copy of confirmed state
const [optimisticLiked, setOptimisticLiked] = useOptimistic(liked);When no Action is running, optimisticLiked always equals liked. They can differ only while an Action is in progress.
- Compute from what the user sees
const next = !optimisticLiked;It flips optimisticLiked, not liked, because the user is reacting to what is on screen; two quick taps toggle the way the user expects.
- Start the Action
startTransition(async () => {Passing an async function to startTransition makes it an Action. React keeps the optimistic value until that function finishes.
- Confirmed update after await
startTransition(() => setLiked(saved));Because it comes after an await, it is wrapped again so React handles it as part of the Action.
- Failure path
setError('Could not save. Please try again.');liked was never changed, so the button returns to Like as soon as the Action ends; this line only explains what happened.
Clicking Like turns the button into "Liked" immediately, with aria-pressed="true". If saveLike() resolves, the button keeps showing the value the server returned. If it rejects, the button falls back to "Like" and the alert "Could not save. Please try again." appears.Form actions and an optimistic list item
When you pass a function to <form action={fn}>, React calls it with the FormData on every submit and runs it as an Action, so you no longer need preventDefault. After the Action succeeds, React resets the uncontrolled inputs. Giving useOptimistic an update function as its second argument lets you show a temporary item in a list.
const [comments, setComments] = useState(initialComments);
const [shown, addPending] = useOptimistic(comments, (current, text) => [
...current,
{ id: 'pending', text, sending: true },
]);
async function submit(formData) {
const text = formData.get('text');
addPending(text);
const saved = await postComment(text);
startTransition(() => setComments((c) => [...c, saved]));
}
// <form action={submit}><input name="text" /><button>Send</button></form>
// {shown.map((c) => <li key={c.id}>{c.text}{c.sending && ' (sending…)'}</li>)}Return expected errors as state
With useActionState, return validation errors and answers like "name already taken" as state, for example { error: '...' }, instead of throwing. That keeps the message inside the form.
In real projects
In real projects
Optimistic UI fits actions that are quick and easy to undo: liking, bookmarking, marking a task done, sending a chat message. For actions that cannot be undone, such as paying, deleting an account or buying a ticket, show success only after the server confirms. There, disabling the button with isPending and showing "Processing…" is more honest.
Chat apps usually render an optimistic message slightly faded with a "sending" marker, so the user can tell which items are not confirmed yet. When sending fails, removing the item is not enough; showing a Retry button as well gives a much better experience. Teams also log failed optimistic actions, because a rollback the user barely noticed still means their data was not saved.
Common mistakes
Common mistakes
Calling the optimistic setter outside an Action
Calling setOptimisticLiked(next) directly in onClick makes React warn that an optimistic update happened outside a transition or action, and the value may vanish at once. Call it only inside startTransition or a form action.
Getting the useActionState parameter order wrong
useActionState calls your action with (previousState, formData). Writing async function save(formData) puts the previous state in that parameter, and you get "formData.get is not a function". Naming the parameters prevState and formData keeps the order obvious.
Making irreversible actions optimistic
Showing "Payment successful" early and then failing can make the user close the page believing they bought something. A rollback fixes the screen, not the decision the user already made.
Best practices
Best practices
- Mark optimistic items, for example with "sending", so they look different from confirmed ones
- On failure, roll back and also tell the user what happened with a role="alert" message
- Put the server's answer into confirmed state, not the value you sent
- Throttle the network in DevTools and watch the pending and rollback states with your own eyes
Mini challenge
A rename-project form with useActionState
Write a form that renames a project. The action validates the input, calls a fake server function, and returns either the new name or an error message as state. While saving, the submit button shows "Saving…".
- Write renameProject(previousState, formData) and pass it to useActionState
- Return an error without calling the server when the name is shorter than 3 characters
- Catch a server throw and put the error in state, keeping the old name
- Read pending with useFormStatus inside a SaveButton component
import { useActionState } from 'react';
import { useFormStatus } from 'react-dom';
async function saveProjectName(name) {
await new Promise((resolve) => setTimeout(resolve, 500)); // fake network
if (name.toLowerCase() === 'admin') throw new Error('That name is reserved.');
return name;
}
export async function renameProject(previousState, formData) {
// TODO: read and trim formData.get('name')
// TODO: too short -> return previous name + an error
// TODO: try saveProjectName; success -> { name, error: '' }
// TODO: catch -> keep previous name, error: err.message
}
function SaveButton() {
// TODO: useFormStatus() -> disabled + 'Saving…' while pending
}
export default function RenameProject() {
// TODO: useActionState(renameProject, { name: 'Untitled', error: '' })
// TODO: <form action=...> with heading, labelled input, SaveButton, alert
}Expected: It starts with "Project: Untitled". Submitting "ab" shows "Use at least 3 characters.". Submitting "Roadmap" shows "Saving…" briefly, then the heading reads "Project: Roadmap". Submitting "admin" shows "That name is reserved." and keeps the old name.
Show hint
Whatever object the action returns becomes the state for the next render, so on errors remember to return name: previousState.name. useFormStatus only works in a component rendered inside the <form>.
Show solution
import { useActionState } from 'react';
import { useFormStatus } from 'react-dom';
async function saveProjectName(name) {
await new Promise((resolve) => setTimeout(resolve, 500)); // fake network
if (name.toLowerCase() === 'admin') throw new Error('That name is reserved.');
return name;
}
export async function renameProject(previousState, formData) {
const name = String(formData.get('name') ?? '').trim();
if (name.length < 3) {
return { name: previousState.name, error: 'Use at least 3 characters.' };
}
try {
const saved = await saveProjectName(name);
return { name: saved, error: '' };
} catch (err) {
return { name: previousState.name, error: err.message };
}
}
function SaveButton() {
const { pending } = useFormStatus();
return (
<button type="submit" disabled={pending}>
{pending ? 'Saving…' : 'Save'}
</button>
);
}
export default function RenameProject() {
const [state, formAction] = useActionState(renameProject, {
name: 'Untitled',
error: '',
});
return (
<form action={formAction}>
<h2>Project: {state.name}</h2>
<label>
New name <input name="name" />
</label>
<SaveButton />
{state.error && <p role="alert">{state.error}</p>}
</form>
);
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- An Action is an async function run inside a transition, so React knows it is pending
- A useOptimistic value exists only during the Action and falls back to confirmed state on failure
- Wrap state updates that come after await in startTransition again
- useActionState passes (previousState, formData) and returns [state, formAction, isPending]
- Do not make irreversible actions optimistic
useOptimistic — React