Sub topic 5
Designing the state shape
This chapter assumes you know React function components and useState, the HTML FormData API, and async functions. It also assumes you have seen the basic useActionState call: const [state, formAction, isPending] = useActionState(action, initialState).
The hook accepts any value as state. React does not care whether it is an object, an array, a number, or a string. The shape you choose decides how simple the action function is, how easy the component is to read, and how many bugs show up when a submission fails. This chapter covers how to choose that shape.
What the state is for
In useActionState, the state is the result of the last submission. The first time the form renders, the state is the initial value you passed. After each submission, the state is whatever the action function returned.
The action receives the previous state as its first argument and the submitted FormData as its second. It returns the next state. Because the previous state is an input, the state is also a small piece of memory that carries across submissions.
Three kinds of information usually belong in it:
- The outcome of the last submission, such as success or failure.
- Messages to show the user, such as validation errors.
- Values the user typed, so you can show them again after React resets the form.
Information that does not come from a submission does not belong here. Whether the form is pending is already given by isPending. Values the user is still typing, before any submission, stay in the DOM or in useState.
Start from what the component must render
A good way to pick a shape is to list what the component needs to draw after a submission, then give each item a field.
For a newsletter form, the component needs to know:
- Did the last submission succeed?
- If not, what error message should appear?
- What email should be in the input?
That list gives this shape:
const initialState = {
ok: false,
error: null,
email: "",
};Each field maps to one piece of UI. The error field drives the alert paragraph. The ok field drives the thank-you message. The email field drives the input's defaultValue.
Here is the full component. The action returns a complete new state object on every path.
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>
);
}Notice that the failure branch returns the submitted email. React resets an uncontrolled form after a successful action, so without that field the user would lose what they typed. The success branch returns an empty string so the input is cleared for the next entry.
Return the whole state every time
The action's return value replaces the previous state. React does not merge it. If you return only { error: "Bad email" }, the ok and email fields disappear, and the component will read undefined for them.
There are two common ways to avoid this:
- Return every field on every path, as
subscribedoes above. - Spread the previous state and override what changed.
async function subscribe(prevState, formData) {
const email = String(formData.get("email") ?? "");
if (!email.includes("@")) {
return { ...prevState, ok: false, error: "Enter a valid email address.", email };
}
return { ...prevState, ok: true, error: null, email: "" };
}Spreading is shorter when the state has many fields. Returning every field is more explicit and makes stale values less likely. A stale value is one left over from an earlier submission. With spreading, a field you forget to override keeps its old value, so an old error message can survive a later success.
Pick a shape that fits the data
The state can take several forms. The right one depends on what the form produces.
| Shape | Good for | Example |
|---|---|---|
| Object with named fields | Most forms with errors and success flags | `{ ok, error, email }` |
| Array | A list that grows with each submission | `["milk", "eggs"]` |
| Number or string | A single value updated by the action | A counter |
| Discriminated object with a `status` field | Forms with more than two outcomes | `{ status: "error", ... }` |
Arrays and other plain values
The state does not have to be an object. This list form uses an array, and each submission builds the next array from the previous one.
import { useActionState } from "react";
async function addItem(prevItems, formData) {
const name = String(formData.get("name") ?? "").trim();
if (!name) return prevItems;
return [...prevItems, name];
}
export function ShoppingList() {
const [items, formAction] = useActionState(addItem, []);
return (
<form action={formAction}>
<input name="name" type="text" />
<button type="submit">Add</button>
<ul>
{items.map((item, i) => (
<li key={i}>{item}</li>
))}
</ul>
</form>
);
}The empty-input branch returns prevItems unchanged. Returning the same reference is a valid way to say "nothing happened." Never mutate prevItems with push. Always return a new array so the change is visible to React.
A status field for more than two outcomes
Booleans like ok work for two outcomes. When a form can end in three or more, such as idle, invalid, failed, and saved, several booleans can contradict each other. For example, ok: true and error: "..." can both be set. A single status field removes that possibility.
const initialState = { status: "idle", message: null, values: { email: "" } };
async function subscribe(prevState, formData) {
const email = String(formData.get("email") ?? "").trim();
if (!email.includes("@")) {
return {
status: "invalid",
message: "Enter a valid email address.",
values: { email },
};
}
try {
const res = await fetch("/api/subscribe", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email }),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
} catch {
return {
status: "failed",
message: "We could not reach the server. Try again.",
values: { email },
};
}
return { status: "saved", message: "Thanks for subscribing.", values: { email: "" } };
}The component can then branch on one value instead of testing combinations of flags. Keeping the typed values under a values key also separates what the user entered from what the system reports.
Keep derived data out of state
State should hold facts that the action produced. Anything you can compute from those facts should be computed during render.
If the state has error, you do not need a second field called hasError. Use Boolean(state.error) or just state.error && in the JSX. Storing both lets them drift apart. The same applies to isPending. React gives you that value, so do not store a submitting field in your own state.
Design for field-level errors
A form with several inputs usually needs one error per field. Use an object keyed by field name.
const initialState = { errors: {}, values: { name: "", email: "" } };
async function register(prevState, formData) {
const values = {
name: String(formData.get("name") ?? "").trim(),
email: String(formData.get("email") ?? "").trim(),
};
const errors = {};
if (!values.name) errors.name = "Name is required.";
if (!values.email.includes("@")) errors.email = "Enter a valid email address.";
if (Object.keys(errors).length > 0) {
return { errors, values };
}
// save the user here
return { errors: {}, values: { name: "", email: "" } };
}In the component, read state.errors.name and state.errors.email next to the matching inputs, and set each input's defaultValue from state.values. Because the action replaces the whole state, old errors vanish on the next submission without any extra code. That is a benefit of returning a complete object.
Keep the state serializable
If you later move the action to a server function, the state crosses the network between server and client. React can only send serializable values, such as strings, numbers, booleans, plain objects, and arrays. Class instances and functions will not survive. Choose plain data now and you avoid a rewrite later.
For the same reason, avoid putting File objects or large payloads in state. Keep only what the UI needs to render.
Common mistakes in state design
- Returning a partial object, which drops the other fields.
- Mutating
prevStateinstead of returning a new value. - Forgetting to return typed values on the error path, so the form clears.
- Storing
isPendingor other derived data in state. - Using several booleans for outcomes that exclude each other.
- Returning
undefinedon some path, which makes the next render read properties ofundefined.
The last one is easy to cause. An early return; for an empty form leaves the state as undefined, and state.error then throws. Always end every branch with a return of the full shape.
Exercise
A registration action returns { errors } when validation fails, and { errors: {}, values: { name: "", email: "" } } on success. The component reads state.values.name for the input's defaultValue. After a failed submission, the page throws an error. What is wrong, and how do you fix it?
Show answer
The failure branch returns only { errors }, and the returned value replaces the state. state.values is now undefined, so reading state.values.name throws. The fix is to return the full shape on every path: return { errors, values }. This also keeps what the user typed. Spreading prevState first ({ ...prevState, errors, values }) would also avoid the crash.
Exercise
A form can end as idle, invalid, failed, or saved. You currently track this with the booleans invalid, failed, and saved. Name one problem with this design and describe a replacement.
Show answer
Three booleans can hold impossible combinations, such as saved: true and failed: true, and each branch of the action must remember to reset the other two. Replace them with a single status field whose value is "idle", "invalid", "failed", or "saved". The component then branches on one value.