Nextjs Fundamentals · Server Functions & Mutations

Form state and validation

useActionState

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.

  1. useActionState returns the state, a form action, and a ___ flag.
  2. useActionState is imported from react.
  3. The action wrapped by useActionState runs in the browser.
  4. The second argument to useActionState is the ___ state.
  5. A Server Action can report a validation error by returning a state object instead of throwing.