Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Worked example · 25 min · revision 2

Form Actions and Pending States in React

Submit a form to a React action, receive errors back as state, show a pending state that doubles as double-click protection, and keep server-side validation non-negotiable.

Contentsand lesson path

What you will learn

  • Handle submission in React with controlled or uncontrolled inputs and form actions (useActionState, useFormStatus), including pending state, double-submit prevention and server-returned errors, treating server-side validation as mandatory.

Prerequisites: React Components & State

01. The problem

The classic React form wires onSubmit, calls preventDefault, reads the fields, sets submitting to true, sends the request, and untangles three possible endings in a try/catch/finally. Every form repeats this dance, and each hand-rolled version has its own bugs: a submitting flag that never resets after an error, a disabled button that flickers because the flag was set in the wrong order, an error message stored in state nobody renders.

React 19 moves this into the framework. A <form> accepts an action: a function that receives the fields and runs as a transition. useActionState wraps that action so its result becomes renderable state, and useFormStatus lets a button read the submission's pending state without any prop drilling. This walk-through builds a profile form on those three pieces and checks what they do — and do not — guarantee against double submission. The validation examples stay deliberately small; the schema-driven version of the same form is the lab.

Everything here composes with the two lessons before it. Native constraints keep declaring what valid means, and the browser still runs them before a submit event fires. The reporting rules stay the same too: errors are text tied to fields with aria-describedby, not colours. What changes is who owns the submit path and the pending state — and the answer is React, not a hand-rolled flag.

02. Step 1: an action that returns state

An action is an async function. When React calls it through useActionState, it receives two arguments: the previous state, and the submitted fields as FormData. Whatever it returns becomes the new state. That shape decides your error strategy for you: expected failures — a validation error, a taken username — are data, returned like any other state, while only genuine surprises should throw (a thrown error bypasses your form and lands in the nearest error boundary). The mock action below stands in for a server action; in a Next.js app it would live in a file marked "use server", but the signature and the return value are the same.

TypeScript · profile-form.tsx, part 1
import { useActionState } from 'react';
import { useFormStatus } from 'react-dom';

export type SaveState = {
  status: 'idle' | 'error' | 'saved';
  errors: Record<string, string>;
};

// A mock server action: it receives (previous state, FormData) and
// returns the next state. Expected failures come back as data.
export async function saveProfile(
  _prev: SaveState,
  formData: FormData,
): Promise<SaveState> {
  await new Promise((resolve) => setTimeout(resolve, 300)); // network
  const email = String(formData.get('email') ?? '');
  const bio = String(formData.get('bio') ?? '');
  const errors: Record<string, string> = {};
  if (!/^\S+@\S+\.\S+$/.test(email)) {
    errors.email = 'Enter a valid email address.';
  }
  if (bio.length > 140) {
    errors.bio = 'Keep the bio under 140 characters.';
  }
  if (Object.keys(errors).length > 0) return { status: 'error', errors };
  return { status: 'saved', errors: {} };
}

03. Step 2: render the returned state

useActionState(saveProfile, initial) returns three things: the current state, the action to put on the form, and isPending (a boolean showing if the transition is running). In the form below, SubmitButton reads pending from useFormStatus instead so the button can be extracted cleanly without prop drilling. The form renders errors straight from state, and each message is wired the way the constraint-validation lesson wired static pages: aria-describedby names the message element, aria-invalid marks the field, and the success note is a role="status" region so its insertion is announced.

TypeScript · profile-form.tsx, part 2
function SubmitButton() {
  const { pending } = useFormStatus(); // reads the <form> that holds it
  return (
    <button type="submit" disabled={pending}>
      {pending ? 'Saving…' : 'Save profile'}
    </button>
  );
}

export function ProfileForm({ action = saveProfile }: { action?: typeof saveProfile }) {
  const [state, formAction] = useActionState(action, { status: 'idle', errors: {} });
  return (
    <form action={formAction}>
      <label htmlFor="email">Email</label>
      <input
        id="email"
        name="email"
        type="email"
        required
        aria-invalid={state.errors.email ? true : undefined}
        aria-describedby={state.errors.email ? 'email-error' : undefined}
      />
      {state.errors.email ? <p id="email-error">{state.errors.email}</p> : null}

      <label htmlFor="bio">Bio</label>
      <textarea
        id="bio"
        name="bio"
        aria-invalid={state.errors.bio ? true : undefined}
        aria-describedby={state.errors.bio ? 'bio-error' : undefined}
      />
      {state.errors.bio ? <p id="bio-error">{state.errors.bio}</p> : null}

      <SubmitButton />
      {state.status === 'saved' ? <p role="status">Profile saved.</p> : null}
    </form>
  );
}

SubmitButton is a separate component on purpose: useFormStatus reads the state of the <form> that contains the component calling it, so calling it in the component that renders the form sees no form at all. Note one React 19 behaviour that surprises people: when an action finishes without throwing, React resets the form's uncontrolled fields — and returning an error state counts as finishing. In a check with this form, an email and a bio typed before a submit that came back with an error were both empty afterwards. To keep what the user typed across a validation failure, return the submitted values in the error state and bind them back as defaultValue (or keep those fields controlled), as the lab does.

Where the action runs is a deployment detail the component does not care about. Pass a function defined in the same client bundle and it runs in the browser. In a Next.js app you pass a server action — the same signature, marked "use server" — and React posts the FormData to an endpoint it generates, so the code runs on the server with the form still hydrating. That is progressive enhancement for free: the submission works before the JavaScript arrives, which is exactly why the server-side parse cannot be skipped — the endpoint exists whether or not your client code is loaded to guard it.

04. Step 3: run it and watch the guarantees

The tests below use Testing Library, with the Vitest and jsdom setup from the lab. The first drives a rejected save: a well-formed address that the mock server refuses, because the browser's native type="email" check would otherwise stop the submit event before the action ever runs — native constraints and actions stack, they do not compete. The second catches the pending state and submits the form a second time while the first action is still running.

TypeScript · actions.test.tsx (Vitest 5.1.2, Testing Library 16.3.3)
import { act } from 'react';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { beforeEach, expect, it } from 'vitest';
import { ProfileForm, type SaveState } from './profile-form';

let calls = 0;
let resolvers: Array<() => void> = [];
beforeEach(() => {
  calls = 0; // each test counts its own action calls
  resolvers = [];
});
const slowSave = async (
  _prev: SaveState,
  formData: FormData,
): Promise<SaveState> => {
  calls += 1;
  await new Promise<void>((resolve) => {
    resolvers.push(resolve);
  });
  const email = String(formData.get('email') ?? '');
  if (email.startsWith('taken@')) {
    return { status: 'error', errors: { email: 'That email is already registered.' } };
  }
  return { status: 'saved', errors: {} };
};

const releaseAll = () => {
  for (const resolve of resolvers) resolve();
  resolvers = [];
};

it('renders server-returned errors next to the fields', async () => {
  const user = userEvent.setup();
  render(<ProfileForm action={slowSave} />);
  await user.type(screen.getByLabelText('Email'), '[email protected]');
  await user.click(screen.getByRole('button', { name: 'Save profile' }));
  releaseAll();
  const message = await screen.findByText('That email is already registered.');
  const input = screen.getByLabelText('Email');
  console.log('after a failed save, #email-error reads ->',
    JSON.stringify(message.textContent));
  console.log('email aria-invalid ->', input.getAttribute('aria-invalid'));
  console.log('email aria-describedby ->', input.getAttribute('aria-describedby'));
  expect(input.getAttribute('aria-invalid')).toBe('true');
  expect(input.getAttribute('aria-describedby')).toBe('email-error');
});

it('shows the pending state and serialises a second submission', async () => {
  const user = userEvent.setup();
  render(<ProfileForm action={slowSave} />);
  await user.type(screen.getByLabelText('Email'), '[email protected]');
  await user.click(screen.getByRole('button', { name: 'Save profile' }));
  await waitFor(() => expect(screen.getByRole('button').textContent).toBe('Saving…'));
  const button = screen.getByRole('button') as HTMLButtonElement;
  console.log('while the action runs ->', button.textContent,
    '| disabled =', button.disabled);
  expect(button.disabled).toBe(true);
  // Submitted again while the first action is still running:
  await act(async () => {
    fireEvent.submit(document.querySelector('form')!);
  });
  console.log('action calls started while one was pending ->', calls);
  expect(calls).toBe(1); // React 19.3 queues it, it does not run concurrently
  releaseAll(); // the first action returns
  await waitFor(() => expect(calls).toBe(2)); // then the queued one starts
  releaseAll();
  await screen.findByText('Profile saved.');
  console.log('after both finished ->', calls, 'action calls, button reads',
    button.textContent);
  expect(button.textContent).toBe('Save profile');
  expect(button.disabled).toBe(false);
});
Expected output
after a failed save, #email-error reads -> "That email is already registered."
email aria-invalid -> true
email aria-describedby -> email-error
while the action runs -> Saving… | disabled = true
action calls started while one was pending -> 1
after both finished -> 2 action calls, button reads Save profile

Read the last three lines as the honest picture of double-submit protection. disabled={pending} is real: while the action runs the button is disabled and reads "Saving…", so a second click — the ordinary accident — goes nowhere. Submitting the form again through a different path does not start a second action either: React 19.3 serialises submissions per form, and the queued submission only runs after the first returns (the count reaches 2 at that moment). But that queuing is an implementation detail you should not build on, and no client-side trick covers a second tab, a retry, or a crafted request. The durable guarantee is the server's: the action re-validates and the database enforces uniqueness. Client signals manage the experience; the server protects the data.

05. Check your understanding

Practice check · 3 questions

Actions and state in practice

Three decisions inside the profile form.

Q1. Why does an action passed to useActionState receive the previous state as its first argument?
Q2. Inside the action, how do you read what the user typed into the field named bio?
Q3. The submit button sets disabled={pending} from useFormStatus. Which submission path does that NOT stop?
Practice only: not graded, not saved, not evidence.

06. Apply it

Extend profile-form.tsx:

  1. Add a website field that the action rejects unless it starts with https://, and render its message with the same aria-describedby wiring.
  2. Make the action return a status: 'saving' variant and check what the button shows — then delete it and keep pending, because the framework already tracks that.
  3. Write a test in the style of this lesson: submit, and while the action is pending assert the button is disabled and the form has aria-busy if you add it.

Then read the useFormStatus reference and the form element docs and note one behaviour each that surprised you.

07. Review prompt

Without looking back: what are the two arguments of an action used with useActionState, and what happens to its return value? Why are expected failures returned rather than thrown? Where must a component sit for useFormStatus to see a form, and what does pending give you? Which double-submission paths does disabled cover, and which guarantee has to come from the server?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check