Sub topic 4
How forms reset after an Action
This chapter assumes you can write function components with useState, and that you know what an uncontrolled input is. It also assumes you have read the earlier chapters on passing a function to <form action> and on the Actions model. Here you will learn when React clears a form for you, which inputs are affected, and how to keep or force the reset.
What React does after the Action finishes
When you pass a function to a form's action prop, React runs it as an Action. When that Action completes, React resets the form. This is the same reset the browser performs when a user clicks <button type="reset">. Each uncontrolled field goes back to its default value, which is the defaultValue or defaultChecked attribute, or empty if there is none.
You do not call anything to get this behavior. This example clears the field after every submission:
import { useState } from "react";
export function TodoList() {
const [todos, setTodos] = useState([]);
async function addTodo(formData) {
const title = String(formData.get("title") ?? "").trim();
if (title === "") return;
await new Promise((resolve) => setTimeout(resolve, 500));
setTodos((current) => [...current, title]);
}
return (
<div>
<form action={addTodo}>
<input name="title" />
<button type="submit">Add</button>
</form>
<ul>
{todos.map((title, index) => (
<li key={index}>{title}</li>
))}
</ul>
</div>
);
}Type a title and press Add. About half a second later the todo appears in the list and the input is empty. Before React 19 you would have written event.preventDefault(), read the values, and cleared the input yourself.
Timing
The reset is tied to the end of the Action, not to the moment of the click. The order is:
- The user submits the form.
- React calls your function with the form's
FormDataand marks the transition as pending. - Your function awaits its work and calls state setters.
- When the function's promise resolves, React commits the resulting state updates.
- React resets the form.
The user keeps seeing what they typed while the request is in flight. The field only clears once the work is done, so it never goes blank and then flashes the old value back.
What gets reset and what does not
The reset is the DOM's form.reset(). It only knows about the form's own default values, so its effect depends on how each input is wired.
| Input style | Example | After the Action |
|---|---|---|
| Uncontrolled, no default | `<input name="title" />` | Cleared |
| Uncontrolled with default | `<input name="title" defaultValue="Untitled" />` | Back to the current `defaultValue` |
| Controlled | `<input value={title} onChange={...} />` | Still shows `title`, because the state did not change |
| Form triggered by `onSubmit` | `<form onSubmit={...}>` | Not reset by React |
A controlled input shows whatever its state says. The reset does not change your state, so React keeps rendering the same value and the field looks untouched. To clear a controlled field you set its state yourself:
import { useState } from "react";
export function ControlledTodoForm({ onAdd }) {
const [title, setTitle] = useState("");
async function addTodo() {
await onAdd(title);
setTitle("");
}
return (
<form action={addTodo}>
<input
name="title"
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
<button type="submit">Add</button>
</form>
);
}Mixing the two styles is the usual source of confusion. If you mix them, it is hard to predict which fields clear. Pick one style per field and stay with it.
The common surprise: errors wipe the form
The reset happens whenever the Action completes, and a returned validation error counts as completing. Consider a form that uses useActionState and returns { error: "Email is invalid" } when validation fails. The Action finished normally, so React resets the form and the user's typed text disappears. The error message appears next to an empty field, which is frustrating on a long form.
The fix is to return the submitted values with the error, then feed them back through defaultValue. The reset restores the field to its default value, and that default is now what the user typed.
import { useActionState } from "react";
async function signUp(previousState, formData) {
const email = String(formData.get("email") ?? "").trim();
const displayName = String(formData.get("displayName") ?? "").trim();
if (!email.includes("@")) {
return { error: "Enter a valid email address.", email, displayName };
}
if (displayName.length < 2) {
return { error: "Display name needs at least 2 characters.", email, displayName };
}
await new Promise((resolve) => setTimeout(resolve, 500));
return { error: null, email: "", displayName: "" };
}
export function SignUpForm() {
const [state, formAction, isPending] = useActionState(signUp, {
error: null,
email: "",
displayName: "",
});
return (
<form action={formAction}>
<input name="email" type="email" defaultValue={state.email} />
<input name="displayName" defaultValue={state.displayName} />
<button type="submit" disabled={isPending}>
Sign up
</button>
{state.error && <p role="alert">{state.error}</p>}
</form>
);
}There are two cases. On a validation failure, the Action returns the typed values, defaultValue receives them, and the reset leaves them in place. On success, the Action returns empty strings, so the reset leaves the form blank. One pattern covers both outcomes, and the form never needs a manual clear.
One detail matters here. Before the reset runs, React has already committed the new state, so each input's defaultValue is the new value when the reset happens. This is why returning the values in state works.
Resetting early with a ref
Sometimes you want the field to clear immediately, not after the request finishes. A chat box is the standard case. With optimistic UI, the message already appears in the list, so the input should empty at once. You can call reset() on the form through a ref at the start of the Action:
import { useRef } from "react";
export function QuickNote({ saveNote }) {
const formRef = useRef(null);
async function formAction(formData) {
const text = String(formData.get("note") ?? "");
formRef.current.reset();
await saveNote(text);
}
return (
<form action={formAction} ref={formRef}>
<input name="note" />
<button type="submit">Save</button>
</form>
);
}Read the values from formData before you reset. The FormData object is a snapshot taken at submit time, so it stays valid after the reset. The Thread component from the optimistic updates chapter uses this same technique.
Resetting when you do not use the action prop
Suppose you need onSubmit, for example to inspect the event or to build the request yourself. React will not reset that form on its own. You can still get the same timing by calling requestFormReset from react-dom inside a transition:
import { useTransition } from "react";
import { requestFormReset } from "react-dom";
export function NoteForm({ saveNote }) {
const [isPending, startTransition] = useTransition();
function handleSubmit(event) {
event.preventDefault();
const form = event.currentTarget;
const note = String(new FormData(form).get("note") ?? "");
startTransition(async () => {
requestFormReset(form);
await saveNote(note);
});
}
return (
<form onSubmit={handleSubmit}>
<input name="note" />
<button type="submit" disabled={isPending}>
Save
</button>
</form>
);
}requestFormReset does not clear the form immediately. It schedules the reset for when the surrounding transition ends, which matches the behavior of <form action>. Two details are worth knowing:
- Call it synchronously at the start of the transition function, before the first
await. After anawait, React can no longer tell which transition the call belongs to. - Capture
event.currentTargetinto a variable first. Do not read it from the event after anawait, because by then the event no longer points at the form.
How to choose
| You want | Do this |
|---|---|
| Clear on success, with no extra code | Use uncontrolled inputs with `<form action={fn}>` |
| Keep typed values when validation fails | Return the values from `useActionState` and use them as `defaultValue` |
| Clear the field before the request ends | Call `formRef.current.reset()` early in the Action |
| Use `onSubmit` but keep React's timing | Call `requestFormReset(form)` inside `startTransition` |
| Clear a controlled input | Set its state in the Action |
Edge cases to check
- Fields with a
defaultValuethat changes. The reset uses the most recently rendered default, not the value from first render. This is what makes the sign-up pattern work. It also means a staledefaultValuefrom old state restores an old value. - Checkboxes and radios. They go back to
defaultChecked, not to unchecked. A checkbox that wasdefaultCheckedends up checked again after every submission. - Several forms on one page. Each form is reset on its own. One form's Action does not reset another.
- Thrown errors. If an Action throws, the error goes to the nearest error boundary. For failures you expect, such as a rejected request, catch them and return an error object instead of throwing.
- File inputs. A reset clears the selected file, so an upload form that fails will make the user pick the file again. A file input cannot be restored from state, so say so in the error message.
Exercise
A form uses useActionState. When the user submits an invalid email, the error message appears but the email field is empty. The Action returns { error: "Invalid email" }. Why does the field clear, and what two changes fix it?
Show answer
The Action completed normally, so React reset the form and the uncontrolled input went back to its default value, which was empty. First, return the submitted value from the Action, for example { error: "Invalid email", email }. Second, pass that value to the input as defaultValue={state.email}. The reset then restores the typed value.
Exercise
You wrote a form with <form onSubmit={handleSubmit}> that calls startTransition(async () => { await save(); }). The fields never clear. Which function do you add, where do you call it, and why must it come before the first await?
Show answer
Add requestFormReset(form) from react-dom, calling it inside the startTransition function with the form element. React does not reset forms handled through onSubmit, so you ask for the reset yourself, and it runs when the transition ends. It must come before the first await because after an await React can no longer tell which transition the call belongs to.