Next.js useActionState
useActionState shows the result of an action on the page. The form stays put, and the answer appears under it.
The form holds the action answer
The hook runs addBook and holds its answer. The form shows the field errors and the message.
'use client';
import { useActionState } from "react";
import { addBook } from "@/app/actions";
export default function AddBookForm() {
const [state, formAction, isPending] = useActionState(addBook, null);
return (
<form action={formAction}>
<p>
<label>Title <input name="title" /></label>
{state?.errors?.title && <span> {state.errors.title[0]}</span>}
</p>
<p>
<label>Author <input name="author" /></label>
{state?.errors?.author && <span> {state.errors.author[0]}</span>}
</p>
<button type="submit" disabled={isPending}>
{isPending ? "Saving..." : "Add book"}
</button>
{state && <p>{state.message}</p>}
</form>
);
}The shape of the answer
The answer is null before the first submit. After a submit it holds ok, a message, and any errors.
export type AddBookState = {
ok: boolean;
message: string;
errors?: { title?: string[]; author?: string[] };
} | null;Example
node -e 'const state = { ok: false, message: "The book was not saved. Fix the errors below.", errors: { title: ["Title is required"] } }; console.log(state.message); console.log("Title:", state.errors.title[0]);'Key points
- useActionState: the hook that runs an action and holds its answer
- The hook gives three things: the last answer, the form action, and a pending flag.
- Pending means the action is still running. The button shows Saving... while it runs.
- The answer holds a message and any field errors. The form shows both.
- The page never reloads. The answer appears where the form already is.
- ?. is the safe read. state?.errors means the errors, or nothing when the answer is still null.
In this example, the script prints a failed answer in the shape the action returns. The message says the book was not saved, and the title error says Title is required. On the page, the message prints under the form, and the title error prints beside the title field. The button shows Saving... while the action runs, then the answer takes its place. That swap happens in the browser, so curl cannot show it.
Note
The pending label and the answer text are browser-visible. Curl shows the form, not the submit.
Try it Yourself
Edit the code, then press Run.
Running is simulated · TypeScript Playground
Exercise
What does useActionState give the form?