Form actions

Topic 2 of 3 in Forms7 min readIntermediateFree course

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:

JSX
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:

  1. prevents the default page reload,
  2. calls your function with a FormData object containing the fields (by their name),
  3. 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:

JSX
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:

JSX
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.' };
  }
}

Submitting the form sets isPending to true and disables the button; your action runs and awaits saveSignup; it returns new state containing either an error or ok. The code shows useActionState(signup, { error: null }) and an async signup(prevState, formData) function that validates the email, saves it and returns the result.

  • 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:

JSX
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:

JSX
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:

JSX
<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:

JSX
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 name attribute to appear in FormData. A missing name is the most common reason formData.get() returns null.

Exercise

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.

JavaScript
import { useActionState } from 'react';
import { useFormStatus } from 'react-dom';

// provided: subscribe(email) returns a promise

export function NewsletterSignup({ subscribe }) {
  // your code here
}

Summary

  • Pass a function to <form action={fn}>; React calls it with the FormData and 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() from react-dom lets any component inside the form read pending.
  • After a successful action, React resets uncontrolled fields; use defaultValue from state to keep values after errors.