Lesson 20 of 37Modern React
Actions and Optimistic UI
Handle mutations the React 19 way: Actions, useActionState, useFormStatus, and useOptimistic updates that roll back on failure.
Reading data is half of a product. The other half is changing it: posting a comment, liking a photo, moving a card on a board, saving a profile. Each mutation needs the same supporting cast: a pending state, a disabled button so nobody double-submits, an error message that does not wipe what the user typed, and ideally a UI that updates before the server answers. Teams used to hand-roll all of that with useState flags and try/finally in every handler. React 19 turned the pattern into first-class APIs called Actions, and interviewers now expect you to know them.
What an Action is
In Transitions, Suspense and Deferred Values you saw that startTransition accepts an async function in React 19, and that isPending stays true while it runs. That is the whole definition: an Action is a function that runs inside a transition, usually async, usually performing a mutation.
const [isPending, startTransition] = useTransition();
function handleSave() {
startTransition(async () => {
const error = await saveProfile(draft);
startTransition(() => {
if (error) setError(error);
else setSaved(true);
});
});
}Running mutations as transitions gives you four things for free:
- Pending state.
isPendingcovers the whole async function. - No flashing. Any re-render the mutation causes is a transition, so visible content is not replaced by Suspense fallbacks.
- Optimistic updates through
useOptimistic, covered below. - Error handling. If an Action throws, React shows the nearest error boundary, the subject of the next lesson.
Forms are the most common place you meet Actions. Passing a function to <form action={fn}> (or to a button's formAction) tells React to run it as an Action when the form submits. React builds the FormData for you, there is no preventDefault, and when the Action finishes without throwing, React resets the form's uncontrolled fields. If you need a reset in your own code, requestFormReset(form) from react-dom does it inside a transition.
A naming convention has grown up around this. Components that take a callback they will call inside a transition name the prop action or give it an Action suffix (submitAction, changeAction). When you see that suffix in a design system, you know the component will handle pending state for you.
useActionState in depth
The Forms lesson introduced useActionState with a subscribe form. Here are the parts that matter once it is in production code.
const [state, dispatchAction, isPending] = useActionState(action, initialState, permalink?);Your action receives the previous state first and the payload second (the FormData when it is wired to a form). Whatever it returns becomes the new state. That shape makes it a reducer that is allowed to be async.
Errors are state. Expected failures (validation, "that username is taken", a 409 from the API) should be returned, not thrown. Thrown errors go to an error boundary and replace part of the UI, which is the right response to a bug and the wrong response to a typo.
The reset gotcha. The form resets whenever the Action finishes without throwing, and that includes the case where you returned a validation error. Without care, the user's text vanishes along with your error message. The fix is to return the submitted values in your state and feed them back as defaultValue. Try a comment shorter than five characters and watch the fields survive, then post a real one and see the comment box clear while the name stays.
Calls are queued. Because each call needs the previous state, useActionState runs calls one after another, never in parallel. Click the button below three times quickly and read the log: each request starts only when the last one has returned.
That queue is often exactly what you want for a cart or a counter, because it removes a whole class of ordering bugs. It also means a slow request delays every click behind it, so for independent operations (liking five different posts) use separate Actions instead of one shared queue.
Two smaller rules. When you call dispatchAction yourself instead of through a form, call it inside startTransition, or React warns and isPending will not update. And the optional third argument, permalink, is for progressive enhancement with Server Functions: if the user submits before JavaScript has loaded, the browser navigates to that URL and the framework renders the result there. It only matters in a framework that supports it.
useFormStatus for nested buttons
A design system usually owns the submit button. useFormStatus (from react-dom) lets that button read its form's state without props:
const { pending, data, method, action } = useFormStatus();The rule people get wrong: it reports the status of the parent <form> of the component that calls it. Call it in the same component that renders the <form> and it always says pending: false, because that component is outside the form. In the demo above, SubmitButton is a separate component rendered inside the form for exactly this reason. data holds the FormData being submitted, handy for "Sending to ada@example.com..." messages.
useOptimistic: show the result before the server answers
A like that takes 400 ms to light up feels broken. Optimistic UI shows the expected result immediately and corrects itself if the server disagrees.
const [optimisticState, addOptimistic] = useOptimistic(state, updateFn);You pass the real state (from useState, props, or server data) and an updateFn(current, payload) that returns the optimistic version. While an Action is running, calling addOptimistic(payload) makes the hook return updateFn(state, payload). When the Action finishes, the optimistic layer is thrown away and the hook returns plain state again.
That last sentence is where automatic rollback comes from. On success, your Action updated the real state, so the real value already contains the change and the swap is invisible. On failure, the real state never changed, so the optimistic item simply disappears. You do not write any undo code.
Send a normal message, then one containing the word "fail".
Notice the second startTransition after the await, for the reason you saw in the previous lesson. Without it the final setMessages would be urgent and could commit before the optimistic layer is removed, briefly showing the message twice.
The form runs send as an Action. Inside it, addOptimistic adds a pending item.
Two details seniors know:
- Optimistic updates are rebased. If the real
statechanges while an Action is still pending (another message arrives over a websocket), React rerunsupdateFnon top of the new state. WriteupdateFnas a pure function ofcurrentand the payload, never a closure over stale data, and nothing gets lost. - Calling
addOptimisticoutside an Action does nothing useful. React warns, because there is no transition whose end would remove the optimistic value.
The same reducer style covers deletes and edits: (current, id) => current.filter((t) => t.id !== id) for a delete, or mark the item { ...item, pending: true } if you would rather grey it out than hide it.
CheckoutForm renders <form action={pay}> and, in the same function, calls useFormStatus() to disable its button. The button never disables. Why?Ordering and races
Optimistic UI is only safe if the final state is right, and multiple submits are where it goes wrong. Picture a like button that sends toggleLike(postId). The user taps three times quickly: like, unlike, like. Three requests go out. The network does not promise order, so the server might apply them as like, like, unlike, and the post ends up unliked while the screen says liked.
The fixes, roughly in the order teams reach for them:
- Send intent, not toggles.
setLike(postId, true)is idempotent: applying it twice gives the same result. The last request the server processes still wins, but each request carries the full truth. - Serialize.
useActionState's queue guarantees order on the client. Good for a counter, slower for rapid taps. - Ignore stale responses. Tag each request with an increasing number and only accept a response that matches the latest one, the same idea as the
ignoreflag in Data Fetching. - Let the server be the source of truth. Return the new state from the mutation (
{ liked: true, count: 42 }) and store that, rather than computing it on the client. - Disable while pending. The simplest fix for forms where double submits cost money, like checkout. Pair it with an idempotency key on the server so a retried request cannot charge twice.
The server takes 400 ms per call. The user clicks Add one three times within 100 ms. What does the paragraph show 1.5 seconds later?
async function addToCart(previous, amount) {
await delay(400);
return previous + amount;
}
function Cart() {
const [count, dispatch] = useActionState(addToCart, 0);
return (
<>
<p>Items: {count}</p>
<button onClick={() => startTransition(() => dispatch(1))}>Add one</button>
</>
);
}With or without a framework
Everything in this lesson works in a plain client app built with Vite. The Action is just an async function that calls your API with fetch.
In a framework that supports React Server Components, the same action can be a Server Function: an async function marked "use server" that runs on the server while the client calls it like a local function. React's docs call these Server Functions; when one is passed to a form's action it is often called a Server Action, which is the name Next.js uses. The hooks do not change: useActionState, useFormStatus and useOptimistic work the same, and permalink lets the form work before hydration. The Next.js course's Server Actions and Forms lesson builds this end to end.
One warning that belongs in every review of server mutations: a Server Function is a public HTTP endpoint. Anyone can call it with any arguments. Validate the input, check the user is allowed to do the thing, and keep React and your framework patched; the Server Components protocol has had serious security fixes (including a critical remote code execution bug in late 2025), and staying current is part of the job.
Order what happens when a user likes a post with an optimistic Action that succeeds.
- Tap the steps below in the right order.
Match each API to its job.
- Action
- A function, usually async, that runs inside a transition. Forms run their
actionprop as one. - useActionState
- Hook returning
[state, dispatchAction, isPending]. The action receives the previous state and a payload; calls are queued in order. - useFormStatus
- A
react-domhook that returnspending,data,methodandactionfor the parent form of the calling component. - useOptimistic
- Hook that returns an optimistic version of state while an Action runs, then falls back to the real state when it ends.
- automatic rollback
- When a failed Action never updates real state, the optimistic value disappears as soon as the Action ends.
- idempotent
- Safe to repeat: applying the same request twice leaves the same result.
setLike(id, true)is;toggleLike(id)is not. - Server Function
- An async function marked
"use server"that runs on the server and can be called from the client, including as a form action.