Form actions
Overview
Submitting a form usually involves the same chores: prevent the page reload, collect the values, set a “submitting” flag, call an API, store the error or success, clear the flag, reset the form. React 19 Actions handle most of that for you, using the browser’s own form model.
Passing a function to action
In plain HTML, a form’s action is a URL. In React 19 you can pass a function:
function SearchForm() {
function search(formData) {
const query = formData.get('q');
alert(`You searched for “${query}”`);
}
return (
<form action={search}>
<input name="q" />
<button type="submit">Search</button>
</form>
);
}When the form is submitted, React:
- prevents the default page reload,
- calls your function with a
FormDataobject containing the fields (by theirname), - resets the form’s uncontrolled fields once the action finishes successfully.
No onSubmit, no e.preventDefault(), no state for every field.
Async actions
Actions can be async. React runs them inside a transition, which means it tracks when they’re pending and keeps the UI responsive while they run:
async function enroll(formData) {
await fetch('/api/enrollments', {
method: 'POST',
body: JSON.stringify({ courseId: formData.get('courseId') }),
headers: { 'Content-Type': 'application/json' },
});
}
<form action={enroll}>
<input type="hidden" name="courseId" value={course.id} />
<button type="submit">Enrol</button>
</form>useActionState: results and errors
Most forms need to show the outcome: a validation error, a server error, a success message. useActionState wraps an action and keeps its latest result in state:
import { useActionState } from 'react';
function SignupForm() {
const [state, formAction, isPending] = useActionState(signup, { error: null });
return (
<form action={formAction}>
<input name="email" type="email" required />
<button type="submit" disabled={isPending}>
{isPending ? 'Signing up…' : 'Sign up'}
</button>
{state.error && <p role="alert">{state.error}</p>}
{state.done && <p role="status">Welcome aboard!</p>}
</form>
);
}
async function signup(prevState, formData) {
const email = formData.get('email');
if (!email.endsWith('.com') && !email.endsWith('.in')) {
return { error: 'Please use a .com or .in address' };
}
try {
await saveSignup(email);
return { error: null, done: true };
} catch {
return { error: 'Something went wrong. Please try again.' };
}
}useActionState(action, initialState)returns[state, formAction, isPending].- Your action receives the previous state first and the form data second. Whatever it returns becomes the new
state. - Pass
formAction(not your original function) to the form.
The action’s return value is the only way to get data out: there’s no separate setError — returning { error } is setting the error.
Keeping values after an error
React resets uncontrolled fields after the action completes, so a user who made one typo would lose everything they typed. Return the submitted values in state and use them as defaultValue:
async function updateProfile(prev, formData) {
const values = Object.fromEntries(formData);
if (values.name.length < 2) {
return { values, error: 'Name is too short' };
}
await saveProfile(values);
return { values, error: null, saved: true };
}
// in the form
<input name="name" defaultValue={state.values?.name ?? ''} />useFormStatus: pending UI anywhere in the form
Submit buttons are often separate components. useFormStatus (from react-dom) lets any component inside a <form> read its status, without props:
import { useFormStatus } from 'react-dom';
function SubmitButton({ children }) {
const { pending } = useFormStatus();
return (
<button type="submit" disabled={pending} aria-busy={pending}>
{pending ? 'Saving…' : children}
</button>
);
}
<form action={formAction}>
…
<SubmitButton>Save profile</SubmitButton>
</form>useFormStatus reads the status of the parent form, so it must be called from a component rendered inside the <form>, not the component that renders the form. It also returns data (the FormData being submitted), method and action.
Several buttons, several actions
A button’s formAction prop overrides the form’s action:
<form action={publish}>
<textarea name="body" />
<button type="submit">Publish</button>
<button type="submit" formAction={saveDraft}>Save draft</button>
</form>Actions outside forms
Actions aren’t limited to forms. Any async function passed to startTransition is an action, and useTransition gives you its pending flag:
const [isPending, startTransition] = useTransition();
<button
disabled={isPending}
onClick={() => startTransition(async () => {
await archiveCourse(course.id);
})}
>
{isPending ? 'Archiving…' : 'Archive'}
</button>Combine actions with useOptimistic to update the UI instantly before the server responds — see Mutations and optimistic UI.
Actions vs onSubmit
onSubmit + state |
action + useActionState |
|
|---|---|---|
| Prevent reload | e.preventDefault() |
automatic |
| Read values | controlled state or FormData |
FormData provided |
| Pending flag | your own useState |
isPending / useFormStatus |
| Errors / results | your own useState |
the action’s return value |
| Reset after success | manual | automatic (uncontrolled fields) |
| Works with Server Functions | no | yes (see Server components) |
onSubmit remains perfectly valid — especially with form libraries like React Hook Form (next lesson). Actions shine for straightforward forms and in frameworks with Server Functions, where the same form can even submit before JavaScript loads.
Remember: inputs need a
nameattribute to appear inFormData. A missingnameis the most common reasonformData.get()returnsnull.
A newsletter signup with actions
Build NewsletterSignup using useActionState. The action reads email from the FormData, returns { error: 'Please enter a valid email' } if it has no @, otherwise awaits subscribe(email) (provided) and returns { success: true, email }. Show the error under the input, show “Thanks! Check {email}” on success, and use a separate SubmitButton component with useFormStatus that reads “Subscribing…” and is disabled while pending. Keep what the user typed if there’s an error.
import { useActionState } from 'react';
import { useFormStatus } from 'react-dom';
// provided: subscribe(email) returns a promise
export function NewsletterSignup({ subscribe }) {
// your code here
}import { useActionState } from 'react';
import { useFormStatus } from 'react-dom';
function SubmitButton() {
const { pending } = useFormStatus();
return (
<button type="submit" disabled={pending}>
{pending ? 'Subscribing…' : 'Subscribe'}
</button>
);
}
export function NewsletterSignup({ subscribe }) {
const [state, formAction] = useActionState(async (prevState, formData) => {
const email = String(formData.get('email') ?? '').trim();
if (!email.includes('@')) {
return { error: 'Please enter a valid email', email };
}
await subscribe(email);
return { success: true, email };
}, {});
if (state.success) {
return <p role="status">Thanks! Check {state.email}</p>;
}
return (
<form action={formAction}>
<label htmlFor="email">Email</label>
<input id="email" name="email" type="text" defaultValue={state.email ?? ''} />
{state.error && <p role="alert">{state.error}</p>}
<SubmitButton />
</form>
);
}Summary
- Pass a function to
<form action={fn}>; React calls it with theFormDataand prevents the page reload. - Actions run in a transition: they can be async, and React tracks their pending state.
useActionState(action, initialState)returns[state, formAction, isPending]; the action receives(prevState, formData).useFormStatus()fromreact-domlets any component inside the form readpending.- After a successful action, React resets uncontrolled fields; use
defaultValuefrom state to keep values after errors.