Forms in React 19: Actions, useActionState and useOptimistic
React 19 makes the form the actual interface: a function as the form action, plus three hooks for the result, the pending state and instant UI feedback. This post shows how they work together – and where optimistic rendering breaks down without a clean error path.
An optimistically inserted entry that disappears again on an error and leaves no message behind tells the user something false: they submitted, they saw it briefly, then there was nothing. This is the one place where the form APIs of React 19 create work instead of taking it off your hands – and that is why it comes first, right here at the start.
Everything else about them is relief. Up to React 18, a form that saves a name consisted of onSubmit, event.preventDefault(), a useState for the loading state, a second one for the error message and a try/catch somewhere – a surprising amount of manual work for a surprisingly everyday task. React 19, stable since December 5, 2024, instead hands a function directly to the <form> element and puts three hooks next to it: useActionState, useFormStatus and useOptimistic. They take care of exactly the things you used to wire up by hand. I will go through what each of these building blocks takes over, how they work together and where the error path from the first paragraph belongs.
From onSubmit to action#
The starting point is a small but far-reaching change to the <form> element. In React 19, the action attribute accepts a function – no longer just a URL string as in classic HTML. On submit, this function receives a FormData object and is called by React. React calls preventDefault itself, wraps the call in a transition and – a detail that is easily overlooked – automatically resets an uncontrolled form after a successful action.
Here is the comparison. Before:
function NameForm() {
const [isSaving, setIsSaving] = useState(false);
const [error, setError] = useState(null);
async function handleSubmit(event) {
event.preventDefault();
setIsSaving(true);
setError(null);
const formData = new FormData(event.currentTarget);
const result = await save(formData.get("name"));
setIsSaving(false);
if (result.error) setError(result.error);
}
return (
<form onSubmit={handleSubmit}>
<input name="name" />
<button disabled={isSaving}>{isSaving ? "Saving…" : "Save"}</button>
{error && <p>{error}</p>}
</form>
);
}
And after, with a client action:
function NameForm() {
async function updateName(formData) {
await save(formData.get("name"));
}
return (
<form action={updateName}>
<input name="name" />
<button>Save</button>
</form>
);
}
The second variant is not just shorter, it shifts control. React now knows that a handover is happening here, keeps the pending state consistent and takes care of the native submit behavior. In its documentation, React simply calls a function that triggers transitions this way an “Action”. What the second variant still lacks is everything that actually made up the first code block: the loading state and the error handling. That is exactly what the three hooks bring back – but without the manual work.
Who takes care of what#
At first glance, the three hooks sound similar, but they have very different jobs. So before the code, the responsibilities:
useActionStatebundles the complete lifecycle of an action in one place: it wraps your action function, holds the returned result as state, provides anisPendingflag and hands you back a wrappedformActionthat you attach to the form.useFormStatusreads the pending state of the nearest enclosing<form>– meant for child components like a submit button that don’t need to know anything about the action itself, but want to know whether a submission is in progress.useOptimisticimmediately shows an expected intermediate state while the action is still running, and afterwards automatically converges back to the real state – to the server value on success, to the old value on error.
You can use the three individually or together. In a real form, they usually interlock, and how they work together is exactly where it gets interesting.
useActionState: result and pending in one place#
You import useActionState from react – not from react-dom, which is a common first source of errors. The signature:
const [state, formAction, isPending] = useActionState(action, initialState, permalink);
The decisive point, and a surprising one for many, lies in the signature of the action function you pass in. It does not just receive the FormData; its first argument is the previous state, and only the second is the form data:
import { useActionState } from "react";
async function updateName(previousState, formData) {
const name = formData.get("name");
const error = await save(name);
if (error) {
return { error };
}
return { ok: true };
}
function NameForm() {
const [state, formAction, isPending] = useActionState(updateName, {});
return (
<form action={formAction}>
<input name="name" disabled={isPending} />
<SubmitButton />
{state.error && <p role="alert">{state.error}</p>}
{state.ok && <p>Saved.</p>}
</form>
);
}
What happens here is the entire first code block from above – just without the manual work. The return value of the action becomes the new state, React manages the isPending flag, and formAction is the wrapped function that gets attached to the action attribute. The error message is no longer a separate useState; it simply falls out of the returned state.
When I see in a code review that the state is suddenly undefined or the previous state gets lost, the cause is almost always the same: the action was written as (formData) => … instead of (previousState, formData) => …. The first parameter is simply not the FormData. If you come from the old onSubmit world, this reflex is in your fingers, and it regularly costs a few minutes of searching.
A historical note so that older tutorials don’t confuse you: in the canary versions, this hook was called useFormState and lived in react-dom. With React 19, it was moved to react and renamed to useActionState; the third element isPending was added at the same time. useFormState has been deprecated since – if you still see it somewhere, the code is from an older state.
useFormStatus: reading pending in the child#
Now to the submit button that I already used above as <SubmitButton />. You might ask why it is extracted – after all, I could have passed isPending from useActionState directly to a button in the form. Both are possible, but useFormStatus solves a specific problem: a reusable component that knows the pending state without you having to pass it down.
import { useFormStatus } from "react-dom";
function SubmitButton() {
const { pending } = useFormStatus();
return (
<button disabled={pending}>
{pending ? "Saving…" : "Save"}
</button>
);
}
The hook comes from react-dom, takes no parameters and, in addition to pending, returns data, method and action of the enclosing form. The one rule you need to know, and the one responsible for most of the error reports at this point: useFormStatus reads the status of the nearest parent <form> and therefore has to sit in a child component, not in the same component that renders the <form>.
If the hook accidentally sits in the form component itself, pending is simply always false – from that perspective, there is no enclosing form whose status could be read. The button has to be a child. A separate SubmitButton component is therefore not a matter of taste: without this nesting, the hook sees nothing at all.
useOptimistic: showing the expected state immediately#
The third hook is the most impressive one – and the most dangerous if you only half understand it. useOptimistic immediately shows the state you expect after a successful action, without waiting for the server response. The classic example is a message list in which your own message appears immediately:
import { useOptimistic, useActionState } from "react";
function Thread({ messages, sendMessage }) {
const [optimisticMessages, addOptimistic] = useOptimistic(
messages,
(currentMessages, newText) => [
...currentMessages,
{ text: newText, sending: true },
]
);
const [state, formAction] = useActionState(
async (previousState, formData) => {
const text = formData.get("message");
addOptimistic(text);
const error = await sendMessage(text);
if (error) {
return { error };
}
return { ok: true };
},
{}
);
return (
<div>
<ul>
{optimisticMessages.map((message, index) => (
<li key={index}>
{message.text}
{message.sending && <span> (sending…)</span>}
</li>
))}
</ul>
<form action={formAction}>
<input name="message" />
<SubmitButton />
{state.error && <p role="alert">{state.error}</p>}
</form>
</div>
);
}
useOptimistic receives the real state and a pure reducer function that computes the next intermediate state from the current state and the optimistic value. The call to addOptimistic has to happen inside an action or transition – here, inside the async action that useActionState manages. If you call it outside, you get a warning and no optimistic rendering.
The truly elegant part is the automatic convergence: the optimistic value only applies while the action is running. As soon as it has finished, the displayed state falls back to the real messages state. On success, that is the updated server value; on error, the old value – so the optimistically inserted message disappears again on its own. You don’t have to reset anything manually.
The pitfall: optimistic without an error path#
The automatic convergence tempts you to consider the error case done. It isn’t – this is where the bugs come from that nobody sees in testing and everybody reports to support.
Imagine sendMessage fails. The optimistic value is rolled back automatically – the message disappears from the list. From the user’s point of view, that means: they submitted something, it appeared briefly, and then it was gone. Without any further feedback. No user interprets that as “error while sending”; most think they misclicked and simply try again – in the worst case, this creates a duplicate as soon as the server did respond after all.
The flawed reasoning is to mistake useOptimistic for error handling. The hook takes care of the visible intermediate state, not of communicating the result. You have to keep these two jobs apart:
useOptimisticmakes sure the optimistic value is rolled back automatically on an error – that is the rollback of the UI state, and you get it for free.- The visible error message is a separate responsibility. It has to come from the
stateofuseActionState: the action catches the error, returns it as{ error }, and the UI derives a message from it.
With concurrent changes, this UI rollback is not enough. Duplicate submissions, stale server states and conflicts still need idempotency keys, version checks or a domain conflict rule on the server.
That is exactly what happens in the code above: in the error case, the action returns { error }, and {state.error && <p role="alert">…</p>} makes it visible. The optimistic value disappears automatically, but the user sees why. If, on the other hand, you swallow the error in the catch or never return it in the first place, you have a UI that, on errors, silently gives the false impression that nothing happened. Optimistic rendering without a real error path is worse than no optimistic rendering at all.
How it fits together#
If you arrange the four participants – the form, the action, the pending state and the optimistic value – in time, the pattern becomes clear:
flowchart LR A["form action(fn)<br/>submit triggered"] --> B["isPending = true<br/>button disabled<br/>via useFormStatus"] B --> C["addOptimistic()<br/>expected state<br/>visible immediately"] C --> D["await save()"] D -->|Success| E["real state<br/>state.ok<br/>form reset"] D -->|Error| F["optimistic value reverted<br/>state.error visible"]
The upper path is the normal case, the lower one is the one you have to actively design. React takes almost the entire path from A to D off your hands; the conscious design decision lies in the branch at D – and in making sure the error branch doesn’t lead nowhere.
The second diagram sorts out the responsibilities once more, because the risk of confusing the three is real:
flowchart TB
subgraph Form["React 19 form"]
UAS["useActionState<br/>call + result + pending"]
UFS["useFormStatus<br/>reads pending of the parent form<br/>in the child"]
UO["useOptimistic<br/>instant intermediate state<br/>with auto-convergence"]
end
UAS -->|passes isPending<br/>and state| UI["Error and success display"]
UFS -->|pending| Button["SubmitButton"]
UO -->|optimisticState| Liste["Live list"]A word on Server Functions#
So far, I have talked about client actions – functions that run in the browser. But the same mechanism also carries across the network boundary. With the "use server" directive at the top of a file or a function, you mark Server Functions that can be called from the client but run on the server:
"use server";
export async function updateName(previousState, formData) {
const name = formData.get("name");
await db.users.update({ name });
return { ok: true };
}
You can pass this function to useActionState or directly to <form action={…}> exactly like a client action – the signature is the same. It is important not to confuse "use server" with "use client"; the two directives mark opposite places of execution. And Server Functions require a framework or bundler that supports React Server Components; in a pure client app, they don’t exist.
A nice side effect in this context is progressive enhancement. If you pass a permalink – a URL – to useActionState as the third argument, the form also works when JavaScript hasn’t hydrated yet or isn’t available at all: the browser navigates to this URL the classic way, the server processes the FormData, and as soon as React has hydrated, the client-side action takes over seamlessly. This is only relevant in an RSC context, but it shows that the Actions model was thought through all the way into server communication and is not just a prettier way of writing onSubmit. If you want to dig deeper into this interplay, my post on React Server Components and Server Actions gives you the bigger picture.
What sticks#
All in all, it comes down to a change of perspective. In React 19, you give the form a function; cleaning up after it with event handlers goes away. The three hooks are not three new things to memorize, but the three responsibilities you used to tie together yourself, cleanly separated: useActionState for the call, the result and pending, useFormStatus for the view of pending from the child, useOptimistic for instant feedback with automatic rollback.
The two stumbling blocks that, in my experience, cost the most time: the action of useActionState receives the previous state as its first argument, not the FormData. And optimistic rendering is only done when the error case has a visible message – the hook takes the rollback off your hands, but not the communication. With these two points in mind, forms in React 19 become shorter and more robust than anything you built by hand before.
Further reading#
Revised and translated from German with the help of AI.