Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 72 ยท Mutations and Forms

Building Forms with Server Actions

Build Next.js forms with Server Actions: read FormData, return errors with useActionState, show pending state with useFormStatus and keep user input.

A Server Action can run on the server, but a form is more than a function call. A good form shows a pending state while it works, displays errors next to the right fields, keeps what the user typed when something goes wrong, and still works if JavaScript is slow to arrive. React 19 gives you three tools for this, and Next.js builds on them: the FormData object an action receives, the useActionState hook, and the useFormStatus hook.

This lesson shows the real Next.js code read-only, then lets you run the same patterns as live stand-ins. The stand-ins use real React 19 hooks in your browser. The only fake part is the "server": a function in the same page with a delay, standing in for the network round trip.

Real or stand-in? useActionState and useFormStatus are plain React 19 APIs, so the jsx examples here behave like the real thing. What differs from a Next.js app is that the action runs in the browser instead of on a server, so there is no network, no 'use server' and no progressive enhancement. Everything about the hooks, though, carries over exactly.

Reading FormData

An action called from a form receives a FormData. Each field is read by its name attribute:

TypeScript
// app/actions.ts
'use server';

export async function createPost(formData: FormData) {
  const title = formData.get('title');     // string | File | null
  const body = formData.get('body');
  const tags = formData.getAll('tag');     // all checked boxes named "tag"

  // ... validate, then save
}

formData.get() returns FormDataEntryValue | null, which is a string or a File. It is never a number, so convert on purpose (Number(...)) and never assume a field exists: a hand-crafted request can leave fields out or add extra ones. Handling that safely is the topic of Validating Input.

Returning errors with useActionState

If the action only returns nothing and redirects, there is no way to show "your title is too short". The solution is useActionState. It takes your action and an initial state, and gives you back the latest returned value, a wrapped action for the form, and a pending flag. The action now receives the previous state as its first argument and the FormData second.

TSX
// app/actions.ts
'use server';

export type FormState = {
  message: string;
  errors: { title?: string };
  values: { title: string };
};

export async function createPost(previous: FormState, formData: FormData): Promise<FormState> {
  const title = String(formData.get('title') ?? '').trim();
  if (title.length < 3) {
    return { message: '', errors: { title: 'Use at least 3 characters.' }, values: { title } };
  }
  // await db.post.create(...)
  return { message: 'Saved!', errors: {}, values: { title: '' } };
}
TSX
// app/new-post/form.tsx
'use client';

import { useActionState } from 'react';
import { createPost, type FormState } from '@/app/actions';

const initial: FormState = { message: '', errors: {}, values: { title: '' } };

export function PostForm() {
  const [state, formAction, isPending] = useActionState(createPost, initial);

  return (
    <form action={formAction}>
      <input name="title" defaultValue={state.values.title} />
      {state.errors.title && <p role="alert">{state.errors.title}</p>}
      <button disabled={isPending}>{isPending ? 'Saving...' : 'Save'}</button>
      {state.message && <p>{state.message}</p>}
    </form>
  );
}

Two details matter here. First, the action returns errors instead of throwing, because validation failures are expected outcomes and a thrown error would hit an error boundary. Second, after a form action finishes, React resets uncontrolled fields. That wipes what the user typed, which is why the action sends the submitted values back and the inputs use defaultValue={state.values.title}.

The next example is the same pattern as a live stand-in: a guestbook form. The "server" is a function with a short delay that rejects short names, rejects the name admin and succeeds otherwise. The state shape matches the Next.js code above.

A guestbook form with useActionState

Try submitting empty (two errors appear and the entry count stays 0), then admin with a long message (only the name error shows, and your message is still in the field), then a valid pair (the form clears and the entry appears). That cycle is exactly how a real Next.js form behaves.

Pending UI with useFormStatus

isPending from useActionState works where you call the hook. But often the submit button lives in its own component, and you do not want to pass props down. useFormStatus from react-dom solves this: a component rendered inside a <form> can read the form's status without props.

TSX
'use client';

import { useFormStatus } from 'react-dom';

export function SubmitButton({ children }: { children: React.ReactNode }) {
  const { pending } = useFormStatus();
  return <button type="submit" disabled={pending}>{pending ? 'Working...' : children}</button>;
}

Use it inside any form, with no wiring:

TSX
<form action={createPost}>
  <input name="title" />
  <SubmitButton>Save</SubmitButton>
</form>

The hook returns { pending, data, method, action }. The one that matters most is pending, which is true while the form's action is running. data is the FormData being submitted, which is handy for showing "Saving 'My title'...". There is one important rule: useFormStatus reads the parent form, so it must be called in a component that is a child of the <form>. Calling it in the same component that renders the <form> always returns pending: false.

Several buttons, one form

A single form often needs more than one action: "Save draft" and "Publish". A button inside a form is included in the FormData when it is the one that submitted the form, if it has a name and value. You can read that to tell the buttons apart. This example puts useFormStatus in a reusable button and uses an intent field, with a progress message that shows the data being submitted.

Reusable submit button and two intents

Type a title and press Publish: only that button reads "Working...", both buttons are disabled, the status line shows what is being sent, and then the result appears. Neither button component received any props about the form: useFormStatus found the parent form on its own.

Putting it together in Next.js

A well-built Next.js form usually combines these pieces:

  1. A 'use server' action with the signature (previous, formData) that validates and returns a state object with errors and values.
  2. A small Client Component that calls useActionState and renders the fields.
  3. A shared SubmitButton that uses useFormStatus.
  4. In the action, after success, a call to revalidatePath or redirect (see Optimistic UI and Refreshing After Mutations).

Keep the form component small and push everything that needs the server into the action. The page that renders the form can stay a Server Component, importing the client form as one interactive island. If you want a refresher on that boundary, see Composing Server and Client Components.

Return errors as data, and reserve thrown errors for the unexpected (the database is down). A thrown error from an action reaches the nearest error boundary, so only throw when you want error.tsx to appear.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What are the arguments of an action passed to useActionState?

    useActionState passes the previous state first and the FormData second. The value you return becomes the next state.
  2. 2. Where must useFormStatus be called to report the form's pending state?

    useFormStatus reads the nearest parent form. Called in the component that renders the form itself, it always reports pending as false.
  3. 3. Why does the action return the submitted values along with errors?

    After a form action finishes, React resets the form. Returning the values lets the inputs show what the user typed again.
  4. 4. How can one form tell a 'Save draft' button from a 'Publish' button?

    The submitting button's name and value are included in the FormData, so formData.get('intent') reveals which button was used.
  5. 5. Which is the better way to report 'title is too short'?

    Validation failures are expected, so return them as data. Throwing sends the user to an error boundary.

Summary

  • A form action receives FormData; read fields by name and treat every value as untrusted text or a file.
  • useActionState(action, initialState) returns [state, formAction, isPending]; the action receives (previousState, formData).
  • Return validation errors and the submitted values as data, because React resets uncontrolled fields after the action.
  • useFormStatus gives pending and data to components rendered inside a form, so a reusable SubmitButton needs no props.
  • Buttons with name and value let one form carry several intents.
  • The stand-ins run the real React hooks; only the server is simulated.

Next: Validating Input