Sub topic 5
Designing the state shape
This chapter assumes you can write a basic useActionState call. You should know the action receives the previous state and a FormData object, and returns the next state. You should also be comfortable with useState and plain JavaScript objects.
React does not choose the shape for you
useActionState stores whatever your action returns. React does not inspect it. That freedom leaves one design decision to you: what shape the state has.
The component reads this state on every render, including the first render, before anyone has submitted anything. So the initial state you pass in must have the same shape as every result the action can return. If it does not, you will write state.error?.message checks everywhere, or hit a crash on the first render.
Start from what the UI needs to show
List what the screen displays after a submission, then give each item a field.
| UI need | State field |
|---|---|
| Which phase the form is in | `status`: `"idle"`, `"error"` or `"success"` |
| A message for the whole form | `message` |
| An error under each input | `fieldErrors`, an object keyed by input name |
| What the user typed | `values`, an object keyed by input name |
The example below uses all four fields.
import { useActionState } from "react";
const initialState = {
status: "idle",
message: null,
fieldErrors: {},
values: { title: "", body: "" },
};
async function savePost(prevState, formData) {
const values = {
title: String(formData.get("title") ?? "").trim(),
body: String(formData.get("body") ?? "").trim(),
};
const fieldErrors = {};
if (!values.title) fieldErrors.title = "Title is required.";
if (values.body.length < 10) {
fieldErrors.body = "Body needs at least 10 characters.";
}
if (Object.keys(fieldErrors).length > 0) {
return { status: "error", message: "Fix the marked fields.", fieldErrors, values };
}
await fetch("/api/posts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(values),
});
return {
status: "success",
message: "Post saved.",
fieldErrors: {},
values: initialState.values,
};
}
export function PostForm() {
const [state, formAction, isPending] = useActionState(savePost, initialState);
return (
<form action={formAction}>
<input name="title" type="text" defaultValue={state.values.title} />
{state.fieldErrors.title && <p role="alert">{state.fieldErrors.title}</p>}
<textarea name="body" defaultValue={state.values.body} />
{state.fieldErrors.body && <p role="alert">{state.fieldErrors.body}</p>}
<button type="submit" disabled={isPending}>Save</button>
{state.message && <p>{state.message}</p>}
</form>
);
}Every return statement has the same four keys. The component never has to ask whether a field exists.
Model the phase with one field
A status string is easier to maintain than several booleans such as isError and isSuccess. Two booleans allow four combinations, and two of them make no sense. One string allows only the phases you name.
What to keep out of the state
- Pending status. The hook already returns
isPending. Copying it into state creates a second source of truth. - Derived values. If you can compute something from other fields, such as
hasErrorsfromfieldErrors, compute it during render. - Values that do not describe the last submission. Anything unrelated to the result belongs in
useStateor elsewhere.
Choosing between a flat and a nested shape
A flat shape such as { error, email } suits a form with one input. Once a form has several inputs, group related data. Use fieldErrors and values objects keyed by the input name. A new input then needs one key in each object, and the action needs no new top-level field.
The state does not have to be an object at all. A list that grows with each submission can be an array, and a counter can be a number. Pick the smallest shape the UI can render from.
Exercise
A form's action returns { error: "Required" } on failure but { saved: true } on success, and the initial state is null. Name two problems this causes and describe a better design.
Show answer
The shapes differ, so the component needs null checks and existence checks on every read, and the first render can crash on state.error. Better: define one initial state, such as { status: "idle", message: null }, and have every return use the same keys. Use status to tell the phases apart.