Form state and validation
To show validation errors and a pending state around a form, use React's
useActionState hook in a Client Component. It wraps a Server Function and
returns three values: the latest returned state, a wrapped action, and a pending
flag.
'use client';
import { useActionState } from 'react';
import { createPost } from '@/app/actions';
export function Form() {
const [state, formAction, isPending] = useActionState(createPost, {
error: null,
});
return (
<form action={formAction}>
<input type="text" name="title" />
<button disabled={isPending}>Create</button>
{state.error && <p>{state.error}</p>}
</form>
);
}
useActionState is imported from react and runs in the browser, but the action
it wraps is a Server Function: submitting the form still POSTs to the server
and back. The second argument is the initial state; whatever the action returns
becomes the next state.
This is how a Server Action reports a validation failure — it returns a state
object (say { error: 'Title is required' }) instead of throwing, and the client
renders it. isPending lets you disable the submit button or show a spinner
while the round-trip is in flight.
You are about to answer a short quiz on useActionState.