Sub topic 2
How Forms Reset After an Action
Prerequisites: you should know React function components, hooks, JSX, async functions, and the browser FormData API.
When a function is passed to a form’s action prop, React runs it on submit. After the Action completes, React resets the form’s uncontrolled fields. An uncontrolled field is managed by the DOM with defaultValue, rather than by React state.
Controlled fields do not reset automatically. Clear their state yourself. A reset also happens after a successful submission, so preserve values that the user needs when returning validation errors.
import { useActionState } from "react";
import { useFormStatus } from "react-dom";
async function saveProfile(previousState, formData) {
const displayName = String(formData.get("displayName") ?? "").trim();
if (displayName.length < 2) {
return { error: "Use at least two characters.", displayName };
}
const response = await fetch("/api/profile", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ displayName }),
});
if (!response.ok) {
return { error: "The profile could not be saved.", displayName };
}
return { error: null, displayName: "" };
}
function SubmitButton() {
const { pending } = useFormStatus();
return (
<button type="submit" disabled={pending}>
{pending ? "Saving..." : "Save"}
</button>
);
}
export function ProfileForm() {
const [state, formAction, isPending] = useActionState(saveProfile, {
error: null,
displayName: "",
});
return (
<form action={formAction}>
<input name="displayName" defaultValue={state.displayName} />
<SubmitButton />
{isPending && <p>Saving your changes...</p>}
{state.error && <p role="alert">{state.error}</p>}
</form>
);
}useFormStatus reads the status of the nearest parent form. Therefore, SubmitButton must render inside the form. Its pending value becomes true while the form Action is running.
useActionState connects an Action to UI state. The Action receives the previous state and FormData. It returns the next state. The hook returns that state, a form action function, and an isPending flag.
Exercise
Why does a submit button component need to be rendered inside the form when it calls useFormStatus?
Show answer
useFormStatus reads the status of its nearest parent form, so a component outside that form cannot read its submission state.