Sub topic 8
Returning results and validation errors with useActionState
This chapter assumes you know React hooks, FormData, and async/await. It also assumes you can define a Server Function with "use server", as covered in the earlier chapters.
Why a form needs returned state
A Server Function used as a form action can insert a row, but the form has no built-in way to learn that the title was empty. useActionState fills that gap. It calls your action, stores whatever the action returns, and gives that value back to the component on the next render.
const [state, formAction, isPending] = useActionState(action, initialState);stateisinitialStateat first. After each submission it is the value the action last returned.formActionis a wrapped version of your action. Pass it to<form action>.isPendingistruewhile the action runs.
Write the Server Function with a previous-state argument
When an action is wrapped by useActionState, React passes the previous state as the first argument. The FormData moves to second place. The function returns the next state.
// 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 };
}The check runs on the server, so a client cannot skip it. Both return values are plain objects, which the serialization rules allow.
Connect it in a Client Component
// 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 initial state { error: null } has the same shape as what the action returns. This lets the component read state.error on the first render and after every submission.
Returning more than an error
State can carry anything serializable. A common pattern is to return the submitted values along with the error. React resets uncontrolled form fields after an action finishes, so without this the user's text disappears when validation fails.
// In the action
return { error: 'Title is required.', values: { title } };
// In the component
<input name="title" defaultValue={state.values?.title} />Give initialState the same shape, or use optional chaining as shown.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `formData.get is not a function` | The action still has the one-argument signature, so it received `prevState` | Add `prevState` as the first parameter |
| Error message never shows | The action returns `undefined` on some path | Return a state object on every path |
| `state.error` throws on first render | `initialState` lacks the field | Match the shape of the returned state |
| Serialization error | The action returned a class instance, function, or similar value | Return plain objects, arrays, strings, and numbers |
Expected versus unexpected failures
Return empty fields, duplicate titles, and similar user mistakes as state. Throw only for problems the user cannot fix, such as a failed database connection. A thrown error propagates to the nearest error boundary instead of becoming state. A later chapter covers that case.
Exercise
Your action is async function save(formData) { ... } and you wrap it with useActionState(save, { error: null }). Calling formData.get('title') fails. What is wrong, and what is the fix?
Show answer
React passes the previous state as the first argument, so formData actually holds { error: null } or the last returned state. Change the signature to save(prevState, formData).