Sub topic 8
Returning results and validation errors with useActionState
This chapter assumes you have read the earlier chapters. You should know what "use server" marks, how to define a Server Function, and how to pass one to a form's action prop. You also need working knowledge of React hooks, async/await, and FormData.
A form action that only writes to the database leaves the user guessing. Did it work? Was the title rejected? useActionState closes that gap. It lets a Server Function return a value, and it gives your component the latest returned value as state.
The working model
useActionState takes an action function and an initial state. It returns three things:
const [state, formAction, isPending] = useActionState(action, initialState);stateis the value the action returned last time it ran. Before the first run, it equalsinitialState.formActionis a wrapped version of your action. You pass it to<form action={...}>.isPendingistruewhile the action is running.
The wrapped action calls your function with an extra first argument: the previous state. Your function returns the next state. React stores it and re-renders.
The diagram below shows one round trip.
The action signature changes
A Server Function used as a plain form action receives only formData. Once you wrap it in useActionState, it receives (prevState, formData). This is the most common mistake in this area. If you keep the old one-argument signature, formData holds the previous state object, and formData.get throws a TypeError.
// app/actions.js
'use server';
import { db } from './db';
export async function createNote(prevState, formData) {
const title = String(formData.get('title') ?? '').trim();
if (title.length === 0) {
return { error: 'Title is required.' };
}
await db.notes.insert({ title });
return { error: null };
}Two details matter here. First, formData.get returns null for a missing field, so String(... ?? '') avoids the text "null". Second, formData.get can also return a File, and String() on a file gives a meaningless string. Check the type if the field might not be text.
The Client Component wires it up:
// app/NoteForm.js
'use client';
import { useActionState } from 'react';
import { createNote } from './actions';
export function NoteForm() {
const [state, formAction, isPending] = useActionState(createNote, { error: null });
return (
<form action={formAction}>
<input name="title" />
<button type="submit" disabled={isPending}>Add note</button>
{state.error && <p role="alert">{state.error}</p>}
</form>
);
}The initialState shape sets the contract for the whole action. Every return path in the action should produce the same shape, so the component never has to guess which keys exist.
Designing the state shape
A single error string works for one field. Real forms usually need more: errors per field, a success flag, and the values the user typed. A consistent shape keeps the component simple.
// app/actions.js
'use server';
import { db } from './db';
export async function createNote(prevState, formData) {
const title = String(formData.get('title') ?? '').trim();
const fieldErrors = {};
if (title.length === 0) {
fieldErrors.title = 'Title is required.';
} else if (title.length > 100) {
fieldErrors.title = 'Title must be 100 characters or fewer.';
}
if (Object.keys(fieldErrors).length > 0) {
return { ok: false, fieldErrors, values: { title } };
}
await db.notes.insert({ title });
return { ok: true, fieldErrors: {}, values: { title: '' } };
}// app/NoteForm.js
'use client';
import { useActionState } from 'react';
import { createNote } from './actions';
const initialState = { ok: false, fieldErrors: {}, values: { title: '' } };
export function NoteForm() {
const [state, formAction, isPending] = useActionState(createNote, initialState);
return (
<form action={formAction}>
<label htmlFor="title">Title</label>
<input
id="title"
name="title"
defaultValue={state.values.title}
aria-invalid={Boolean(state.fieldErrors.title)}
aria-describedby="title-error"
/>
{state.fieldErrors.title && (
<p id="title-error" role="alert">{state.fieldErrors.title}</p>
)}
<button type="submit" disabled={isPending}>Add note</button>
{state.ok && <p role="status">Note added.</p>}
</form>
);
}Why the action returns the submitted values
React resets uncontrolled form fields after a form action finishes. Without help, a user whose submission failed validation would see their input vanish next to the error message. Returning values and feeding them back through defaultValue restores what they typed. On success, the action returns an empty title, so the field clears. Make sure the returned values contain only data you are willing to send back to the browser. Never echo a password field.
What the returned state may contain
The returned value travels from the server to the client, so it must follow the serialization rules from earlier in this tutorial. Plain objects, arrays, strings, numbers, booleans, null, undefined, Date, Map, and Set are fine. Class instances, functions, and symbols are not.
This affects error handling. Returning an Error object is a trap. Return a message string or a code string instead. Do the same for database results. Pick the fields you want rather than returning a raw row object that may hold unexpected types or private columns.
Behavior to know before you ship
Submissions run one at a time
If the user submits again while an earlier submission is pending, React queues the actions. Each one receives the state returned by the one before it. This keeps prevState meaningful. It also means a slow action delays later ones. Disabling the button with isPending, as shown above, avoids accidental double submits.
Progressive enhancement
If the Server Function is passed to useActionState from a framework that supports it, the form can submit before JavaScript loads. The browser sends a normal form POST, and the server renders the page with the returned state. For this to work, the form must be rendered with the action reference that the framework can serialize. useActionState also accepts an optional third argument, a permalink URL. It tells the framework where to navigate for a no-JavaScript submission when the action would redirect. Most apps do not need it. Check your framework's documentation before relying on either behavior.
Call formAction from a form or a transition
formAction is designed for the action prop of a <form>. If you call it from an event handler, wrap the call in startTransition. Otherwise React warns that the action was called outside a transition, and isPending does not update properly.
'use client';
import { startTransition, useActionState } from 'react';
import { createNote } from './actions';
export function QuickAdd() {
const [state, formAction, isPending] = useActionState(createNote, { error: null });
function handleClick() {
const formData = new FormData();
formData.set('title', 'Quick note');
startTransition(() => {
formAction(formData);
});
}
return (
<div>
<button onClick={handleClick} disabled={isPending}>Add quick note</button>
{state.error && <p role="alert">{state.error}</p>}
</div>
);
}Validation is not only for display
The checks in the action are the real validation. Client-side attributes such as required improve the experience, but a client can call a Server Function directly with any data. Returning an error object is how the server reports bad input politely. The security chapter covers authentication and ownership checks, which belong in the same function.
Return errors or throw them?
Use the return value for outcomes you expect and the user can fix. Throw for failures you do not expect.
| Situation | What to do | Result in the UI |
|---|---|---|
| Empty or too-long title | Return `{ fieldErrors: ... }` | The form shows the message and keeps the input |
| Duplicate title the user can change | Return an error state | The form shows the message |
| Database is down | Let the error throw | The nearest error boundary renders its fallback |
| User is not signed in | Throw, or redirect | Error boundary or sign-in page |
A thrown error rejects the action and unmounts the form's subtree up to the nearest error boundary, so the user loses the typed input. In production builds, frameworks usually replace the server's error message with a generic one, so internal details do not leak. Do not rely on a thrown message to tell the user what to fix.
Common errors
formData.get is not a function. The action still has the old signature. AddprevStateas the first parameter.- State shows
undefinedafter submission. Some return path in the action returns nothing. Return the full state shape on every path. - Input clears after a validation error. React reset the uncontrolled field. Return the values and use
defaultValue. - A serialization error on return. The state contains a class instance, a function, or an
Error. Return plain data. - A warning about calling an action outside a transition. Call
formActioninsidestartTransition, or use it as a form'saction.
Exercise
A Server Function saveProfile(formData) works as a plain form action. You wrap it in useActionState(saveProfile, { error: null }) and now every submission throws TypeError: formData.get is not a function. What is wrong, and how do you fix it? Also name one thing the function should return when the display name is empty.
Show answer
With useActionState, React calls the action as saveProfile(prevState, formData). The function still treats its first parameter as the FormData, but that parameter now holds the previous state object, which has no get method. Change the signature to saveProfile(prevState, formData). For an empty display name, return an error state with the same shape as the initial state, for example { error: 'Display name is required.' }, instead of throwing, so the form can show the message and the user can correct it.
Exercise
Your form shows a validation error, but the title the user typed disappears each time. Why does this happen, and what two changes in the action and the component fix it?
Show answer
React resets uncontrolled form fields after a form action completes. To keep the input, return the submitted values in the action's state, for example { fieldErrors, values: { title } }, and set the input's defaultValue from state.values.title in the component.