Sub topic 4
Writing the action function
This chapter assumes you know React function components and useState, the browser FormData API, and async/await. It also assumes you have seen useActionState called with an action and an initial state. The focus here is the function you pass as the first argument: what it receives, what it must return, and where it goes wrong.
The contract
An action function for useActionState has this shape:
async function action(previousState, formData) {
// do work
return nextState;
}React calls it with two arguments and treats its return value as the new state.
previousStateis the state before this submission. On the first call it is the initial state you gaveuseActionState. On later calls it is whatever the previous call returned.formDatais aFormDataobject built from the form that was submitted. It holds the current value of every named field.- The return value becomes the next state. It can be a plain value or a promise for one.
This is the main difference from the action you would pass directly to <form action={...}>. A plain form action receives only formData. Once the function is wrapped by useActionState, the state comes first and the form data second. Forgetting this is the most common first mistake. Code that reads formData.get("email") from the first parameter fails with "get is not a function", because the first parameter is now your state.
A complete example
The example below validates a sign-up form and returns the result as state. It is a complete file and runs in a React 19 project.
import { useActionState } from "react";
const initialState = { status: "idle", errors: {}, values: { name: "", email: "" } };
async function signUp(previousState, formData) {
const name = String(formData.get("name") ?? "").trim();
const email = String(formData.get("email") ?? "").trim();
const values = { name, email };
const errors = {};
if (name.length < 2) errors.name = "Name must have at least 2 characters.";
if (!email.includes("@")) errors.email = "Enter a valid email address.";
if (Object.keys(errors).length > 0) {
return { status: "invalid", errors, values };
}
const response = await fetch("/api/sign-up", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(values),
});
if (response.status === 409) {
return {
status: "invalid",
errors: { email: "That email is already registered." },
values,
};
}
if (!response.ok) {
throw new Error(`Sign-up failed with status ${response.status}`);
}
return { status: "success", errors: {}, values: { name: "", email: "" } };
}
export function SignUpForm() {
const [state, formAction, isPending] = useActionState(signUp, initialState);
return (
<form action={formAction}>
<label>
Name
<input name="name" defaultValue={state.values.name} />
</label>
{state.errors.name && <p role="alert">{state.errors.name}</p>}
<label>
Email
<input name="email" defaultValue={state.values.email} />
</label>
{state.errors.email && <p role="alert">{state.errors.email}</p>}
<button type="submit" disabled={isPending}>
{isPending ? "Signing up..." : "Sign up"}
</button>
{state.status === "success" && <p>You are signed up.</p>}
</form>
);
}The function does five things in a fixed order. It reads the fields, normalizes them, validates them, performs the side effect, and returns a state object. Keeping that order makes actions easy to read and test.
Reading values from FormData
formData.get(name) returns a string, a File, or null. It never returns undefined, and it returns null when no field with that name exists. For text inputs, coerce explicitly:
const title = String(formData.get("title") ?? "").trim();The ?? "" step matters. String(null) is the text "null", which would pass a non-empty check. Falling back to an empty string first avoids that.
Other cases to remember:
- Checkboxes and multi-selects can submit several values under one name. Use
formData.getAll("tags"), which returns an array. - An unchecked checkbox is absent from
FormData.formData.get("agree")returnsnull, so test withformData.get("agree") === "on"orformData.has("agree"). - File inputs give you
Fileobjects. CallingString()on one produces"[object File]". Object.fromEntries(formData)is a quick way to get all fields as an object, but it keeps only the last value for repeated names.
Field values are always strings, so convert numbers yourself with Number(...) and check for NaN.
What to return
React stores whatever you return and re-renders with it. Three rules keep the state predictable.
Return the same shape on every path
In the example, every return has status, errors, and values. The component can then read state.errors.email without checking whether errors exists. If one branch returned { error: "..." } and another returned { errors: {} }, you would need defensive checks everywhere in the render code.
Never mutate the previous state
Treat previousState as read-only and build a new value:
// Wrong: same reference, React may skip the update
previousState.items.push(name);
return previousState;
// Right
return { ...previousState, items: [...previousState.items, name] };If you have nothing to change, returning previousState itself is fine and is the correct way to say "no change".
Echo the submitted values when you reject input
React resets uncontrolled form fields after an action completes. If validation fails and you return only an error message, the user's input disappears. Returning values and using it as defaultValue, as the example does, brings the text back. Form reset has its own chapter, so only the mechanism matters here: the action is where you decide what to carry forward.
Expected failures versus unexpected ones
The example treats these differently on purpose.
| Situation | What to do | Why |
|---|---|---|
| Empty or malformed input | Return state with an error | The user can fix it, and the form stays on screen |
| Server says "already exists" (409) | Return state with an error | Also a user-fixable condition |
| Network down, 500 response, bug | Throw | The form cannot fix it, so an error boundary should handle it |
When an action throws, React does not set state. The error propagates to the nearest error boundary, and any actions queued behind it are cancelled. If you have no error boundary, the component tree unmounts. Reserve throw for situations where showing an error page is the right outcome. For everything the user can correct, return state.
Note that fetch does not reject on HTTP error statuses such as 404 or 500. It rejects only on network failure. Check response.ok, as the example does, or a failed request looks like a success.
Action versus reducer
The signature resembles a useReducer reducer, (state, action) => newState, and the hook is related. The differences are practical:
- A reducer must be pure and synchronous. An action can be
async, callfetch, and run other side effects. - A reducer receives an action object you dispatch. An action receives
FormDatawhen used as a form action, or any value you pass when you call the dispatcher yourself. - A reducer runs during rendering and may run twice in development. An action runs in response to a submission, not during render.
Because the function is not run during render, it is the right place for network calls. Do not call it yourself from the component body. Only React should invoke it, through the dispatcher.
Keep the function easy to test
An action that takes (previousState, formData) and returns a value is a plain function, so you can test it without rendering anything:
const formData = new FormData();
formData.set("name", "A");
formData.set("email", "[email protected]");
const result = await signUp(initialState, formData);
console.log(result.errors.name); // "Name must have at least 2 characters."Defining the action at module level, outside the component, also avoids accidentally capturing stale props or state in a closure. If the action needs data from the component, such as a record ID, put it in a hidden input or bind it with action.bind(null, id). With bind, the bound arguments arrive first, so the signature becomes (id, previousState, formData).
Common mistakes
- Reading
formDatafrom the first parameter instead of the second. - Omitting
nameattributes on inputs. Fields without anameare not inFormData. - Returning
undefinedon some path, which makesstateundefined on the next render and breaksstate.errors. - Mutating
previousStateand returning it. - Throwing for ordinary validation problems.
- Treating a non-OK
fetchresponse as success.
Exercise
A teammate's action is async function save(formData) { const title = formData.get("title"); ... }, and it is passed to useActionState(save, { error: null }). It crashes on the first submit with "formData.get is not a function". What is wrong, and what is the fix?
Show answer
With useActionState, React passes the previous state as the first argument and the FormData as the second. formData is actually the state object { error: null }. Change the signature to async function save(previousState, formData).
Exercise
Your action validates an email field and returns { error: "Enter a valid email." } on failure and { ok: true } on success. The component renders state.error.length and crashes after a successful submit. Explain why, and name two ways to fix the action's return values.
Show answer
After success, state.error is undefined because the success object has no error key, so .length throws. Fix it by returning the same shape on every path, for example { ok: false, error: "..." } and { ok: true, error: null }, and by guarding the render with state.error && ....
Exercise
A server returns HTTP 500 when saving. Should the action return an error state or throw, and what happens if it throws?
Show answer
Throw (after checking response.ok), because the user cannot fix a server fault by editing the form. React does not update the state, cancels any queued actions, and passes the error to the nearest error boundary. A user-fixable problem such as a duplicate email should return error state instead.