Sub topic 1
Form actions: passing a function to the form's action prop
React 19 lets you pass a function to a <form> element's action prop. When the user submits the form, React calls that function and gives it the form's data. This chapter explains how that mechanism works. The rest of the tutorial builds on it, because useFormStatus reports on exactly this kind of submission.
Prerequisites
This chapter assumes you already know:
- React function components, props, and the basic hooks (
useState,useEffect). - JSX syntax, including how to pass a function as a prop.
- How plain HTML forms work:
nameattributes on inputs, a submit button, and theFormDatabrowser API. asyncfunctions and promises.
You need React 19 or later, or a framework release that bundles it, such as a current Next.js App Router project. In React 18 the action prop accepts only a string, and passing a function does not give you the behavior described here.
What an action is
In plain HTML, action is a URL. When the user submits the form, the browser sends the field values to that URL and loads the response as a new page.
React extends the prop. In React 19 you can pass a function instead of a URL. React then:
- Intercepts the submit event.
- Prevents the browser's default page navigation.
- Collects the field values into a
FormDataobject. - Calls your function with that object.
A function passed this way is called a form action, or just an action. This is the simplest working example:
'use client';
export default function GreetingForm() {
function greet(formData) {
const name = formData.get('name');
console.log(`Hello, ${name}`);
}
return (
<form action={greet}>
<label>
Name <input name="name" />
</label>
<button type="submit">Greet</button>
</form>
);
}You did not write onSubmit. You also did not call event.preventDefault(), read event.target, or create a FormData yourself. React handles all of that.
The 'use client' directive is needed here because the function is defined inside a Client Component. In a framework without Server Components you can omit it.
Comparing the action approach with onSubmit
Before React 19, most forms used a controlled input for every field and an onSubmit handler.
import { useState } from 'react';
export default function OldStyleForm() {
const [name, setName] = useState('');
function handleSubmit(event) {
event.preventDefault();
console.log(`Hello, ${name}`);
}
return (
<form onSubmit={handleSubmit}>
<input value={name} onChange={(e) => setName(e.target.value)} />
<button type="submit">Greet</button>
</form>
);
}This still works, and it is still the right choice when you need to react to every keystroke, for example to validate as the user types. The action approach differs in four ways:
| Aspect | `onSubmit` handler | `action` function |
|---|---|---|
| Argument received | A submit event | A `FormData` object |
| Default navigation | You must call `preventDefault()` | React prevents it for you |
| Field values | Usually kept in state | Read from the form at submit time |
| Async tracking | You manage a loading flag yourself | React tracks the submission, so hooks like `useFormStatus` can read it |
The last row matters most for this tutorial. Because React runs your function as an action, it knows when the submission starts and when it finishes. That is what makes pending state available without manual bookkeeping.
What happens on submit
The sequence below shows the order of events when a user submits a form with a function action.
Two details in this sequence are easy to miss.
First, the FormData is a snapshot taken at submit time. If the user edits a field while an async action is still running, your function does not see the edit.
Second, React runs the action inside a transition. A transition is React's mechanism for marking an update as non-urgent, so the interface stays responsive while work is in flight. While the transition is running, the submission counts as pending. Components inside the form can read that state, which is the subject of the next chapters.
Reading values from FormData
FormData is a standard browser API, not a React type. These are the methods you will use most often:
| Method | Returns | Use |
|---|---|---|
| `formData.get('name')` | A string, a `File`, or `null` | Read a single value |
| `formData.getAll('tag')` | An array | Read several values with the same name, such as checkboxes |
| `formData.has('name')` | A boolean | Check whether a field was submitted |
| `Object.fromEntries(formData)` | A plain object | Convert all fields, keeping only the last value for repeated names |
Three edge cases cause bugs:
- Inputs without a
nameare skipped. IfformData.get('email')returnsnull, check that the input hasname="email". - Unchecked checkboxes are absent. They do not appear in
FormDataat all, soformData.get('agree')returnsnull. When checked, it returns the string'on'unless you set avalue. - Every value is a string or a file. A number input still gives you a string. Convert it yourself with
Number(formData.get('age')).
Here is a form that handles these cases:
'use client';
export default function SignupForm() {
function signup(formData) {
const email = String(formData.get('email') ?? '');
const age = Number(formData.get('age'));
const interests = formData.getAll('interest');
const agreed = formData.has('agree');
if (!agreed) {
console.log('Terms not accepted');
return;
}
console.log({ email, age, interests });
}
return (
<form action={signup}>
<input name="email" type="email" required />
<input name="age" type="number" min="0" />
<label>
<input type="checkbox" name="interest" value="react" /> React
</label>
<label>
<input type="checkbox" name="interest" value="css" /> CSS
</label>
<label>
<input type="checkbox" name="agree" /> I accept the terms
</label>
<button type="submit">Sign up</button>
</form>
);
}Browser validation attributes such as required and type="email" still run before the action is called. If the browser blocks the submit, your function is never invoked.
Async actions
An action can be an async function. React waits for the returned promise before it considers the submission finished.
'use client';
export default function ProfileForm() {
async function saveProfile(formData) {
await new Promise((resolve) => setTimeout(resolve, 1000));
console.log('Saved', formData.get('name'));
}
return (
<form action={saveProfile}>
<input name="name" placeholder="Name" />
<button type="submit">Save</button>
</form>
);
}This form is pending for about one second after each submit. Right now nothing in the interface shows that. The button looks the same and can be clicked again, which would start a second submission. Fixing that is the job of useFormStatus, which you will meet in the next chapter. For now, note that the pending period exists because the action returned a promise.
A synchronous action finishes immediately, so its pending period is too short to see.
Automatic form reset
When an action finishes, React resets the form's uncontrolled fields to their initial values. An uncontrolled field is one that has no value prop tied to state. In the ProfileForm above, the name input empties itself after the save completes.
This is convenient for "add a comment" or "subscribe" forms. It surprises people who expect the field to keep what the user typed, such as a settings form that should still show the saved value.
If you want a field to keep its value after submission, you have two options:
- Give the input a
defaultValuethat comes from your saved data. After the reset, the field shows that default. - Make the input controlled with
useState. React does not clear a controlled field's state, so the value stays.
Overriding the action per button
A form has one action, but individual buttons can use their own function through the formAction prop. When the user clicks such a button, React calls the button's function instead of the form's.
'use client';
export default function PostEditor() {
function saveDraft(formData) {
console.log('Draft saved:', formData.get('title'));
}
function publish(formData) {
console.log('Published:', formData.get('title'));
}
return (
<form action={saveDraft}>
<input name="title" placeholder="Post title" />
<button type="submit">Save draft</button>
<button type="submit" formAction={publish}>
Publish
</button>
</form>
);
}Pressing Enter inside the text input triggers the form's default submission, so saveDraft runs. Clicking Publish runs publish. Both functions receive the same FormData.
If you would rather use one function for both buttons, give each button a name and value. The clicked button's pair is added to FormData, and you can branch on it:
'use client';
export default function ReviewForm() {
function review(formData) {
const decision = formData.get('decision');
console.log(decision, formData.get('comment'));
}
return (
<form action={review}>
<textarea name="comment" />
<button type="submit" name="decision" value="approve">Approve</button>
<button type="submit" name="decision" value="reject">Reject</button>
</form>
);
}Strings still work
The prop did not lose its original meaning. If you pass a string, the browser performs its normal submission to that URL:
export default function SearchForm() {
return (
<form action="/search" method="get">
<input name="q" />
<button type="submit">Search</button>
</form>
);
}This is useful for forms that should navigate to another page, and it works without any client-side JavaScript. React decides what to do by checking the type of the value: a function becomes an action, and a string behaves like HTML.
Server Actions in brief
In frameworks that support React Server Components, an action can run on the server. You mark a function with the 'use server' directive, and the framework turns it into an endpoint your form can call.
// actions.js
'use server';
export async function createPost(formData) {
const title = formData.get('title');
// Save the post to a database here.
}// NewPostForm.jsx
import { createPost } from './actions';
export default function NewPostForm() {
return (
<form action={createPost}>
<input name="title" required />
<button type="submit">Publish</button>
</form>
);
}From the form's point of view nothing changes. It still passes a function to action, and the function still receives FormData. The difference is where the function runs. Server Actions also let a form work before client JavaScript has loaded, because the framework can fall back to a normal browser submission. A later chapter covers pending UI for Server Actions.
Errors and edge cases
Some behaviors to keep in mind when writing actions:
- Thrown errors reach an error boundary. Because the action runs in a transition, an uncaught exception propagates to the nearest error boundary. If you want to show an inline message, catch the error yourself or use
useActionState, which later chapters compare withuseFormStatus. - Do not return values you expect to see. A plain form action's return value is ignored. To show a result, you need
useActionState. - Submissions can overlap. Nothing stops the user from submitting twice while the first action is running. Disabling the button is your job, and the next chapters show how.
- Event handlers are not actions. A function passed to
onSubmitreceives an event, notFormData. Mixing them up is a common source offormData.get is not a functionerrors. - The function must be defined, not called. Write
action={greet}, notaction={greet()}. The second form runs the function during render and passes its result to the prop.
Why this matters for useFormStatus
useFormStatus does not watch your function directly. It reads the state of the nearest parent <form>, and that state exists because React is tracking the form's action. If you use onSubmit with your own loading flag, the hook has nothing to report. If you pass a function to action, the hook reports pending as true from the moment of submission until the action finishes.
In summary:
- Passing a function to
actionmakes React handle the submit event, buildFormData, and call your function. - The function can be async, and the submission stays pending until it resolves.
- Uncontrolled fields reset after the action finishes.
- A button's
formActionoverrides the form's action for that click. - Server Actions use the same syntax but run on the server.
Exercise
A form has <form action={save}> and an input <input placeholder="Email" />. The save function logs formData.get('email'), but it always logs null. What is wrong, and what happens to the input's text after an async save finishes?
Show answer
The input has no name attribute, so it is not included in FormData. Adding name="email" fixes the null value. After the action finishes, React resets the uncontrolled input, so its text is cleared unless the input uses defaultValue from saved data or is controlled with state.
Exercise
You write <form action={saveDraft()}> and notice that saveDraft runs every time the component renders. Why, and how do you fix it?
Show answer
Adding parentheses calls the function during render and passes its return value to the prop. Pass the function itself instead: <form action={saveDraft}>. React then calls it with FormData only when the form is submitted.