Sub topic 8
Form reset and keeping what the user typed
This chapter covers a behavior of React 19 form actions that surprises many people: after an action runs, React clears the form. You will learn why it happens, how the state returned from useActionState lets you restore the user's input, and which field types need extra care. It assumes you can write function components with hooks, know how FormData works, and have read the earlier chapters on the action function's signature and on returning validation errors as state.
What React does after an action
When you pass a function to a form's action prop, React treats the submission as an action. Actions run inside a transition. When the action finishes, React resets the form's uncontrolled fields, the same way the browser's form.reset() does. An uncontrolled field is one whose value lives in the DOM and not in React state, so it has no value prop.
Resetting returns each field to its default value, the one set by the HTML defaultValue or defaultChecked attribute. A field with no default becomes empty.
The reset is unconditional. It happens whether the action succeeded or returned a validation error. That causes the usual bug. A user types a long message, makes one mistake, and submits. The error appears and the whole form is empty.
import { useActionState } from "react";
async function subscribe(prevState, formData) {
const email = String(formData.get("email") ?? "");
if (!email.includes("@")) {
return { error: "Enter a valid email address." };
}
return { error: null };
}
export function BrokenForm() {
const [state, formAction] = useActionState(subscribe, { error: null });
return (
<form action={formAction}>
<input name="email" type="text" />
<button type="submit">Subscribe</button>
{state.error && <p role="alert">{state.error}</p>}
</form>
);
}If the user types ana.example.com and submits, the error message appears, but the input is blank again. The action never touched the input. React reset it after the action settled.
Why defaultValue fixes it
The reset restores each field to its current defaultValue. React applies the reset in the same render that commits the new state. So when defaultValue reads from state, the reset puts the value you returned back into the field.
The sequence looks like this:
The fix is to return the submitted values as part of the state and read them back into defaultValue:
import { useActionState } from "react";
async function subscribe(prevState, formData) {
const email = String(formData.get("email") ?? "");
if (!email.includes("@")) {
return { ok: false, error: "Enter a valid email address.", email };
}
await fetch("/api/subscribe", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email }),
});
return { ok: true, error: null, email: "" };
}
export function SubscribeForm() {
const [state, formAction, isPending] = useActionState(subscribe, {
ok: false,
error: null,
email: "",
});
return (
<form action={formAction}>
<input name="email" type="text" defaultValue={state.email} />
<button type="submit" disabled={isPending}>
{isPending ? "Subscribing..." : "Subscribe"}
</button>
{state.error && <p role="alert">{state.error}</p>}
{state.ok && <p>Thanks for subscribing.</p>}
</form>
);
}The two return paths do different things on purpose:
- On failure, the action returns
emailunchanged. The reset restores the typed text, and the error appears beside it. - On success, the action returns
email: "". The reset then leaves the field empty, so the form is ready for the next entry.
The reset itself is the right behavior after a successful submission. You do not need to clear fields by hand. You only need to decide which values to give back to the user.
Keeping several kinds of fields
Each input type has its own "default" property, so your state has to carry a value for each one and you have to wire it to the matching prop.
| Field | Prop that survives the reset | Value to return from the action |
|---|---|---|
| Text, email, number | `defaultValue` | The string from `formData.get(name)` |
| `textarea` | `defaultValue` | The string |
| `select` | `defaultValue` on the `select` element | The selected option's value |
| Checkbox | `defaultChecked` | A boolean: `formData.get(name) === "on"` |
| Radio group | `defaultChecked` on each radio | The chosen value, compared per radio |
| Password | Nothing, by design | Return nothing; let it clear |
| File input | Not possible | Ask the user to choose the file again |
Here is a form that handles four of these. It returns every submitted value in one object, so the component stays simple.
import { useActionState } from "react";
const initialState = {
errors: {},
values: { name: "", message: "", topic: "general", copy: false },
sent: false,
};
async function sendFeedback(prevState, formData) {
const values = {
name: String(formData.get("name") ?? "").trim(),
message: String(formData.get("message") ?? "").trim(),
topic: String(formData.get("topic") ?? "general"),
copy: formData.get("copy") === "on",
};
const errors = {};
if (!values.name) errors.name = "Name is required.";
if (values.message.length < 10) {
errors.message = "Write at least 10 characters.";
}
if (Object.keys(errors).length > 0) {
return { errors, values, sent: false };
}
await new Promise((resolve) => setTimeout(resolve, 500));
return { ...initialState, sent: true };
}
export function FeedbackForm() {
const [state, formAction, isPending] = useActionState(
sendFeedback,
initialState
);
const { values, errors } = state;
return (
<form action={formAction}>
<label>
Name
<input name="name" type="text" defaultValue={values.name} />
</label>
{errors.name && <p role="alert">{errors.name}</p>}
<label>
Topic
<select name="topic" defaultValue={values.topic}>
<option value="general">General</option>
<option value="bug">Bug report</option>
<option value="idea">Idea</option>
</select>
</label>
<label>
Message
<textarea name="message" defaultValue={values.message} />
</label>
{errors.message && <p role="alert">{errors.message}</p>}
<label>
<input name="copy" type="checkbox" defaultChecked={values.copy} />
Email me a copy
</label>
<button type="submit" disabled={isPending}>
{isPending ? "Sending..." : "Send"}
</button>
{state.sent && <p>Feedback sent.</p>}
</form>
);
}Two details are worth noticing. The action trims strings before returning them, so the field shows the cleaned value. If you want to show exactly what the user typed, skip the trim() in values and trim only when you validate. Also, on success the action returns initialState spread into a new object with sent: true. That reuses the empty defaults, so you don't repeat them.
Why this is not the same as a stale defaultValue
defaultValue normally matters only on first render. If you change it later, an uncontrolled input does not update its text, because the DOM owns the value. The form reset is what applies the new default. That has two consequences:
- The pattern only works for forms submitted through an action. If state changes for another reason, such as a button that calls
dispatch, the visible text does not change until a reset happens. - If you need the field to take a new default without a submission, give the input a
keythat changes with the data. A new key makes React create a new DOM element, which starts with the new default.
<input
key={state.resetCount}
name="email"
type="text"
defaultValue={state.email}
/>Use key sparingly. Remounting an input also drops its focus and its cursor position.
Controlled inputs and the reset
You can also hold the text in useState and pass it as value. The reset does not clear a controlled input, because React keeps writing the state value back to it. This means the form keeps what the user typed even when the action fails, without any defaultValue work. But it also means you must clear the state yourself after a success.
import { useActionState, useState } from "react";
async function save(prevState, formData) {
const title = String(formData.get("title") ?? "").trim();
if (!title) return { error: "Title is required.", saved: false };
return { error: null, saved: true };
}
export function ControlledTitleForm() {
const [title, setTitle] = useState("");
const [state, formAction] = useActionState(save, {
error: null,
saved: false,
});
async function handleAction(formData) {
await formAction(formData);
}
return (
<form action={formAction}>
<input
name="title"
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
<button type="submit">Save</button>
{state.error && <p role="alert">{state.error}</p>}
</form>
);
}This version has a flaw that is easy to miss. title is never cleared after a successful save, so the old text stays visible next to a "saved" state. Choosing a controlled field puts that cleanup on you. The handleAction helper above is also unused, which is a sign that the controlled approach adds moving parts. For most forms, prefer uncontrolled fields with defaultValue from state. Use controlled inputs when the UI reacts to every keystroke, for example live character counts or formatting as the user types.
Common mistakes
- Forgetting to return the values. If the failure branch returns only
{ error },state.emailisundefinedand the field clears. Return every value the form needs on every code path. - Returning the wrong type. A checkbox needs a boolean for
defaultChecked. Returning the string"on"is truthy, but returning"off"or an empty string for an unchecked box can behave unexpectedly. Compare with=== "on". - Echoing a password. Do not put passwords into state and render them back. Let the field clear and ask the user to type it again.
- Different state shapes per branch. If success returns
{ ok: true }withoutvalues, the next render readsstate.values.nameand throws. Keep one shape. - Using
valueanddefaultValuetogether. React warns when an input has both. Pick one model for each field.
Summary of the approach
- Read every field from
formDatainto avaluesobject at the start of the action. - Validate, and on failure return
{ errors, values }. - On success, return empty or default values so the automatic reset leaves a clean form.
- In the component, feed each uncontrolled field from
state.valuesusingdefaultValueordefaultChecked.
Exercise
A user fills in a form with a name field and a "subscribe to newsletter" checkbox, checks the box, leaves the name empty, and submits. The action returns { error: "Name is required." } and nothing else. After the response, the checkbox is unchecked. Explain why, and show the changes needed in the action's failure return and in the checkbox JSX so the checkbox stays checked.
Show answer
React resets uncontrolled fields after the action finishes, even when it returned an error. The reset restores each field to its default, and the checkbox has no defaultChecked tied to state, so it goes back to unchecked. Fix the action's failure return to include the values, for example return { error: "Name is required.", name: "", newsletter: formData.get("newsletter") === "on" };. Fix the JSX to read it: <input name="newsletter" type="checkbox" defaultChecked={state.newsletter} />. The initial state passed to useActionState must also include newsletter: false so the first render has a defined value.
Exercise
Why does changing defaultValue from state normally not change the text shown in an uncontrolled input, and what makes it work after a form action?
Show answer
An uncontrolled input keeps its current text in the DOM, and React does not rewrite that text when defaultValue changes after mount. After an action, React resets the form in the same commit that applies the new state. The reset sets each field to its current default, which is now the value from state, so the returned value appears in the field.