Sub topic 1
Forms as actions in React 19
React 19 lets you pass a function to a form's action prop. When the user submits the form, React calls your function with the form's data. This chapter covers that mechanism and what React does around it. It is the base for useActionState, which later chapters build on it.
Prerequisites
This chapter assumes you know the following:
- React function components and
useState. - Basic HTML forms:
nameattributes, submit buttons, and theFormDataAPI. - Async functions and promises in JavaScript.
- You are using
reactandreact-domversion 19 or later. In React 18, a function inactionis not supported.
The problem with hand-written submit handlers
Before React 19, a typical form looked like this:
- Keep each field in
useState, or read values from refs. - Attach an
onSubmithandler. - Call
event.preventDefault()so the browser does not reload the page. - Set a
pendingflag, send the request, then set anerrorflag or clear the fields.
Each step is simple. Together they are boilerplate that every form repeats, and it is easy to get wrong. A forgotten preventDefault reloads the page. A forgotten setPending(false) in a catch block leaves a button disabled.
React 19 moves the repeated parts into the framework. The browser already collects field values in FormData, so React hands you that object. It also tracks whether your function is still running.
Passing a function to `action`
In plain HTML, action is a URL, and submitting the form navigates to that URL. In React 19, action can also be a function:
import { useState } from "react";
export function NoteForm() {
const [notes, setNotes] = useState([]);
async function addNote(formData) {
const text = String(formData.get("text") ?? "").trim();
if (!text) return;
// Simulate a network request.
await new Promise((resolve) => setTimeout(resolve, 500));
setNotes((prev) => [...prev, text]);
}
return (
<form action={addNote}>
<input name="text" type="text" />
<button type="submit">Add note</button>
<ul>
{notes.map((note, i) => (
<li key={i}>{note}</li>
))}
</ul>
</form>
);
}Compare this with an onSubmit version:
- There is no event argument and no
preventDefault(). React stops the browser navigation for you whenactionis a function. - The function receives a
FormDataobject. You read fields withformData.get("text"), using thenameattribute of each input. - The inputs are uncontrolled. You did not give them
valueoronChange, so the form needs no state per field. - The function can be
async. React waits for the returned promise.
formData.get() returns FormData.entryValue, which is a string, a File, or null. Wrapping it in String(... ?? "") gives you a string every time. For checkboxes, get returns null when unchecked. For several fields with the same name, use getAll.
What happens on submit
Three points in this sequence matter later in the tutorial:
- The call is wrapped in a transition. React runs the action as a transition, a low-priority update that keeps the page responsive. This is also how React knows the form is pending. The next chapter covers this.
- The form resets. After the action finishes, React resets uncontrolled fields to their initial values. This is the same as calling
form.reset(). It suits "add an item" forms, but it surprises people when an error occurs and the user's input disappears. - Only one action runs at a time per hook. Repeated submissions are queued rather than run in parallel. Later chapters return to this.
Buttons can have their own action
A <button> or <input type="submit"> also accepts a formAction prop. The submitter's action overrides the form's action for that click. This is useful when one form has two different outcomes:
export function PostEditor() {
async function saveDraft(formData) {
console.log("Draft saved:", formData.get("title"));
}
async function publish(formData) {
console.log("Published:", formData.get("title"));
}
return (
<form action={publish}>
<input name="title" type="text" />
<button type="submit" formAction={saveDraft}>
Save draft
</button>
<button type="submit">Publish</button>
</form>
);
}Clicking "Save draft" runs saveDraft. Clicking "Publish", or pressing Enter in the text field, runs publish. Both functions receive the same FormData.
Where React's state fits in
The NoteForm example works, but it has a weakness. The action calls setNotes itself, so the action is tied to the component's state, and nothing in the form describes what the last submission produced. Errors, success messages, and the values the user typed all need extra useState calls.
The useActionState hook fixes this. It takes your action and returns a new action to put in action. React passes the previous result to your function as an extra argument. Your function returns the next result, and React stores it as state. The signature and the exact flow are covered in the next chapters. For now, remember that a form action is a function from submitted data to a side effect, and useActionState extends it to a function from (previous state, submitted data) to the next state.
Edge cases and details
- A string
actionstill works. If you pass a URL string, the browser submits and navigates as it always did. React only intercepts function values. methodandencTypeare ignored for function actions. React submits the data by calling your function, not by an HTTP request, so these attributes have no effect.- State updates after an
await. In React 19,setStatecalls that run after anawaitinside an action are not part of the transition. They still apply and render correctly, but they are treated as ordinary updates. This rarely matters for simple forms. It is one reasonuseActionStateis preferred for results. - Controlled inputs. If you give an input
valueandonChange, the form reset does not clear your state. The input shows whatever your state says. Choose one approach per field: uncontrolled withdefaultValue, or controlled. - Errors thrown from an action go to the nearest error boundary. If you want a message next to the form, return it as state instead. A later chapter shows how.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Calling `event.preventDefault()` in an action | It throws, because the action receives `FormData`, not an event | Remove it. React already prevents navigation |
| Reading `formData.get("email")` with no `name` on the input | Returns `null` | Add `name="email"` to the input |
| Passing `action={addNote()}` | Runs the function during render and passes its result | Pass the function itself: `action={addNote}` |
| Expecting typed text to remain after submit | Uncontrolled fields reset when the action finishes | Return the value as state and use `defaultValue` |
| Using React 18 | A function `action` is not recognized | Upgrade to React 19 |
Summary
- A function passed to
actionreceivesFormDatawhen the form is submitted, and React prevents browser navigation. - Fields are read by
name, so uncontrolled inputs need no per-field state. - React runs the action in a transition and resets uncontrolled fields when it finishes.
formActionon a button gives a single form several outcomes.useActionState, introduced next, adds a result that persists between submissions.
Exercise
A form uses <form action={handleSubmit}> and handleSubmit(formData) calls formData.get("city"). It always returns null, even though the user typed a city. Name the most likely cause and the fix. Then say what you would change if the city should stay in the field after submission.
Show answer
The city input has no name attribute, and FormData is keyed by name. Add name="city" to the input. To keep the city after submission, React's automatic reset must not clear it. Return the submitted city as state (for example with useActionState) and set defaultValue from that state, or make the input controlled.
Exercise
In the PostEditor example, which function runs when the user presses Enter inside the title field, and why?
Show answer
publish runs. Pressing Enter submits the form using its default submit button. That is the "Publish" button, which has no formAction, so the form's own action is used. Only a click on "Save draft" uses saveDraft.