Skip to content
Tutorials Center
My learning

Topics

Lesson 45 of 132 ยท Forms and Actions

Form Actions in React 19

Learn React 19 form actions - pass a function to the form action prop, read FormData, understand the automatic reset, async actions, formAction buttons and server functions.

For years the standard React form looked the same: controlled inputs, an onSubmit handler, event.preventDefault(), then your own code to collect values, track "loading", and clear the fields afterwards. React 19 adds a second way that matches how HTML forms always worked. You give the <form> a function as its action, and React calls that function with the form's data when the user submits.

JSX
<form action={saveProfile}>
  <input name="nickname" />
  <button>Save</button>
</form>

No preventDefault, no state per field, no event.target gymnastics. The function receives a FormData object with every named field. React also handles the housekeeping around it: the page does not reload, the form resets afterwards, and the call runs inside a transition so the page stays responsive. This lesson covers the basics and the details that surprise people. The next lessons build on it with useActionState and useFormStatus and useOptimistic.

Everything here runs in our editor with React 19.3.1. A form action that is a function works on the client; the "server function" variant shown near the end needs a framework such as Next.js and is read-only.

An action is a function that gets FormData

When the form is submitted, React calls your function with one argument: a FormData built from the form's named fields. Only fields with a name appear in it. get('name') returns one value (always a string, or a File for file inputs), getAll('name') returns every value for repeated names such as a group of checkboxes, and Object.fromEntries(formData) turns it into a plain object when each name appears once.

Reading FormData in an action

Tick both extras and press Order. The console shows entries: drink=tea&extras=milk&extras=honey&note= and the page shows the summary. Three details to remember:

  • An unchecked checkbox is simply absent from FormData, so getAll('extras') returns an empty array rather than false values.
  • Every value is a string. A type="number" input still arrives as "42"; convert it yourself.
  • There is no event. If you need the submit button that was pressed, give it a name and value (see below) rather than looking for event.submitter.

The form resets itself

Here is the behaviour that catches almost everyone once. After a function action runs, React resets the form, just like calling form.reset(). Every uncontrolled field goes back to its defaultValue (or empty), checkboxes go back to defaultChecked.

When does it happen? React captures the FormData first, then resets the form right away, and only then does your function run on that captured data, even if your function is async and takes seconds. The demo below proves it: the second form has a slow action, but its field is already empty while the action is still waiting.

When the reset happens

Type into both fields and press the button. The uncontrolled field empties at once, and the log says action starts with "..." followed 150 ms later by action finished: your function saw the data the user submitted, not the cleared form. The controlled field keeps its text, because its value comes from React state and a reset cannot change state. After a reset React re-applies the state, so what you see is what the state says.

This is by design: after a successful save, an empty form is what you want. The surprise comes on failure, which we handle in a moment.

Actions can be async, and run in a transition

The function may return a promise. React treats the call as an Action: it is wrapped in a transition, so while it is pending the current UI stays interactive and state updates you make are batched sensibly. An action can:

  • update state (setSummary(...)), as above;
  • call APIs with await;
  • throw. An error thrown from an action propagates to the nearest error boundary, exactly like an error thrown while rendering.

A subtle rule follows from that: the state updates you make in the part of the action before its first await belong to the transition too, and React shows the result of a transition only when it is ready, which for an async action means when the action has finished. Updates made after an await are ordinary urgent updates and render at once (wrap them in startTransition if you want them grouped; see Transitions, useTransition and useDeferredValue).

That has a surprising consequence for the most natural way to show "saving...": setting a flag at the start of the action. Try it in the left form below.

Why a manual pending flag stays invisible

Press both Subscribe buttons (the console shows every render). The left form uses a manual flag: setStatus('saving') runs first, but the console never logs a render with saving; the button keeps saying "Subscribe" for 200 ms and then the status jumps straight to subscribed [email protected]. The right form uses useFormStatus in a child component: its button says "Saving..." and is disabled while the action is pending. The hook reads the form's pending state from React itself, which is exactly the signal a manual flag cannot give you. You will meet it properly in useFormStatus and useOptimistic, and useActionState (next lesson) returns a pending value too.

One form, several buttons

A button can carry its own action with formAction. The button's action replaces the form's action for that click. Alternatively, give the buttons a name and value; the pressed button's pair is added to FormData. Both are normal HTML ideas that React now supports with functions.

formAction and named submit buttons

Save draft and Publish share one action and tell it apart through intent. Discard runs a different function entirely, and receives no useful form data of its own.

Keeping the user's text when something goes wrong

Because the form resets right after submit, an action that rejects the data wipes the form. That feels bad: the user typed a long comment, the server said "too short", and now the box is empty. Compare the two forms below. Both reject comments under 10 characters.

Losing and keeping input after a rejected action

Type short in each and press Post. The first form reports the rejection and its box is now empty. The second keeps short because the text lives in state, and only clears it (setText('')) after success. For forms where the user's input is precious, either control the fields, or use useActionState, which returns the submitted values from the action so they can be put back as defaultValue. If you need to reset a form by hand, requestFormReset(form) from react-dom does what the automatic reset does; use it when an action finishes successfully through some other path.

When the action throws

An action is not wrapped in a try/catch for you. If it throws, React treats it as an unhandled error in the update. With no error boundary above, the whole app unmounts. For expected failures (validation, "email taken"), return or store an error instead of throwing; save throw for the truly unexpected, and put an error boundary around forms that call APIs.

An action that throws (fails on purpose)

Press the button and the console shows Error: boom: the action failed. No error boundary exists, so the error is uncaught and the form disappears from React's control. In a real app, an error boundary would show a fallback instead.

Progressive enhancement, in one idea

A plain HTML <form action="/save"> works with JavaScript turned off: the browser posts the fields and loads the response. React 19 lets a server-rendered form with a function action do the same: the form can be submitted before React has even loaded, and React then replays it once the page is interactive (hydration). That needs a framework that renders on a server and gives the form a server function. Our in-browser editor has no server, so the next block is read-only: it shows what the code looks like in a framework with Server Functions (Next.js App Router style).

JSX
// Read-only: needs a framework with Server Functions, such as Next.js. Not runnable in our editor.
// app/profile/page.jsx (a Server Component)
async function saveNickname(formData) {
  'use server';
  const nickname = formData.get('nickname');
  await db.profile.update({ nickname }); // runs on the server only
}

export default function ProfilePage() {
  return (
    <form action={saveNickname}>
      <input name="nickname" />
      <button>Save</button>
    </form>
  );
}

The 'use server' directive marks saveNickname as a function that runs on the server; the browser receives a reference, and React sends the form data to it over the network. You write one function, and the framework generates the endpoint. On the client-only apps we build in this track, the action is an ordinary function that you call your own API from.

Action or onSubmit?

Both are fine, and they can live together. A rough guide:

Use action when Use onSubmit when
You want FormData and uncontrolled fields You need the event (for example submitter) or to call preventDefault conditionally
You want the automatic reset and transition Fields are controlled and you need custom control flow
You use useActionState, useFormStatus, useOptimistic You are building on a form library that wires its own submit
You may later move to server functions Your form posts nowhere (a pure client calculator)

Do not set both on one form expecting both to run in a particular order; pick one for the form's main job.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does React pass to a function you give to a form's action prop?

    React builds a FormData from the form's named fields and calls your function with it. There is no event argument.
  2. 2. A form has two checkboxes named extras, and the user ticks neither. What does formData.getAll('extras') return?

    Unchecked checkboxes are not part of form data at all, so getAll finds nothing and returns an empty array.
  3. 3. When does React reset an uncontrolled form after a function action?

    React captures the FormData and resets the form straight away, so even a slow async action sees the submitted data while the fields are already cleared.
  4. 4. How can you keep the text a user typed when the action rejects it?

    State survives the reset, so a controlled field keeps its text. Another option is to return the submitted values from the action and feed them back as defaultValue.
  5. 5. What is the better way to report an expected failure such as a validation error?

    A thrown error goes to the nearest error boundary and, without one, unmounts the app. Expected problems are data: store them and render them.

Summary

  • <form action={fn}> calls fn(formData) on submit; there is no event and no page reload.
  • Only named fields appear in FormData; values are strings, unchecked checkboxes are absent, getAll handles repeated names.
  • React resets the form right after submit, before an async action finishes; controlled fields keep their state.
  • Actions may be async and run in a transition: state set before the first await shows only when the action finishes, so show "pending" with useFormStatus or useActionState, not a manual flag.
  • Use name/value on buttons or formAction to handle several buttons in one form.
  • Return or store errors for expected failures; a thrown error goes to an error boundary.
  • Server functions ('use server') let the same pattern run on a server and enable progressive enhancement, but need a framework.

Next: useActionState