React › Server Actions & Data Mutations

How does the useFormState hook, sometimes called useActionState, let you show validation errors returned from a server action?

Advanced

Answer

This hook connects a form to a server action and also gives you access to the most recent result returned by that action, such as a validation error message, letting you display feedback to the user without manually managing that state separately.
import { useActionState } from 'react';

async function createPost(previousState, formData) {
  'use server';
  if (!formData.get('title')) return { error: 'Title is required' };
  await db.posts.create({ title: formData.get('title') });
  return { error: null };
}

function NewPostForm() {
  const [state, formAction] = useActionState(createPost, { error: null });
  return (
    <form action={formAction}>
      <input name="title" />
      {state.error && <p>{state.error}</p>}
      <button type="submit">Create Post</button>
    </form>
  );
}
Real-world example A signup form shows a clear error message returned directly from its server action when a username is already taken, without needing any separate client side validation state to track that message.

Common follow-ups: What is passed as the previous state argument the very first time the form is submitted?;How does this pattern compare to handling errors with a traditional client side fetch call?