Sub topic 8
Form reset and keeping what the user typed
This chapter assumes you know React function components, useState, and the FormData API. You should also have seen a basic useActionState form with an action function that returns the next state.
What React does after an action
When a <form> uses a function as its action prop, React resets the form after the action finishes. Every uncontrolled field returns to its defaultValue, or to empty if it has none. This holds whether the action succeeded or failed.
The reset is useful after a successful submit, because the form is ready for the next entry. It is a problem after a validation error, because the user loses what they typed.
Return the values in state
The fix is to return the submitted values as part of the next state. Then pass them back to the inputs as defaultValue. The reset puts each field back to its default value, and that default is now what the user typed.
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 statements differ in one field:
- On a validation error, the action returns
emailwith the typed value. After the reset, the input shows it again. - On success, the action returns
email: "". After the reset, the input is empty and ready for a new address.
So the state decides what the reset restores. You control the outcome by choosing what to put in the returned object.
Why not use a controlled input?
You could keep the value in useState and bind it with value and onChange. That works, but it brings back the hand-written state that useActionState is meant to remove. With defaultValue, the input stays uncontrolled. The browser holds the live value while the user types, and React only sets the starting value after each submission.
| Approach | Typing | After an error | Extra code |
|---|---|---|---|
| Uncontrolled, no state value | Browser | Field is cleared | None |
| Uncontrolled with `defaultValue` from state | Browser | Field keeps the typed value | Return the value from the action |
| Controlled with `useState` | React | Field keeps the value | `value`, `onChange`, and a state variable |
Several fields
Return every field you want to keep. A compact way is to return the entries of the form as an object.
async function signUp(prevState, formData) {
const values = {
name: String(formData.get("name") ?? ""),
email: String(formData.get("email") ?? ""),
};
if (!values.name) {
return { values, error: "Name is required." };
}
return { values: { name: "", email: "" }, error: null };
}In the component, read each default from state.values, for example defaultValue={state.values.name}.
Pitfalls
- Passing a
defaultValuethat never changes. If the action does not return the typed value, the reset clears the field. - Returning the typed value after a success. The form then keeps old data when you wanted a fresh one.
- Using
valuewithoutonChange. React then treats the input as controlled and warns that it is read-only.
Exercise
A user submits a form with an invalid email, and the field comes back empty. The action returns { error: "Invalid email" }. What two changes make the field keep the typed text?
Show answer
Return the submitted value from the action, for example { error: "Invalid email", email }. Then set defaultValue={state.email} on the input. React resets the form after the action, and the reset restores the value from defaultValue, which is now what the user typed.
Exercise
After a successful submit, how do you make the form come back empty while still keeping values on errors?
Show answer
Return an empty string for the field in the success branch, such as email: "", and return the typed value only in the error branch.