# React Hook Form

> A complete flow with validation, review and final submission.

Source: https://stepperize.com/docs/v9/react/forms/react-hook-form

This two-step example keeps the two jobs apart: React Hook Form owns the
fields of the profile step, and Stepperize owns the flow, what the step saved
and the final submission.

```bash
npm install @stepperize/react react-hook-form @hookform/resolvers zod
```

## Complete example [#complete-example]

Pass `onFinish` from your application to perform the final request. It should
reject on failure; the flow then stays open and the person can retry.

```tsx title="signup.tsx"
"use client";

import { zodResolver } from "@hookform/resolvers/zod";
import { defineStepper } from "@stepperize/react";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";

const profileSchema = z.object({
  name: z.string().min(1, "Enter your name"),
  email: z.string().email("Enter a valid email"),
});
type Profile = z.infer<typeof profileSchema>;

const signup = defineStepper([
  { id: "profile", title: "Profile", schema: profileSchema },
  { id: "review", title: "Review" },
]);

type Props = { onFinish: (profile: Profile) => Promise<void> };

export function Signup({ onFinish }: Props) {
  return (
    <signup.Provider
      linear
      // `output` is what the schemas produced. Returning the promise keeps the
      // flow pending while it runs, and unfinished if it rejects.
      onFinish={async (output) => {
        if (output.profile) await onFinish(output.profile);
      }}
    >
      <Flow />
    </signup.Provider>
  );
}

function Flow() {
  const stepper = signup.useStepperContext();
  if (stepper.isFinished) return <p role="status">Saved successfully.</p>;

  return stepper.match({
    profile: () => <ProfileForm />,
    review: () => <Review />,
  });
}

function ProfileForm() {
  const stepper = signup.useStepperContext();
  const { register, handleSubmit, formState } = useForm<Profile>({
    resolver: zodResolver(profileSchema),
    defaultValues: stepper.data.profile ?? { name: "", email: "" },
  });

  return (
    <form noValidate onSubmit={handleSubmit((values) => stepper.next(values))}>
      <label>
        Name
        <input {...register("name")} aria-invalid={!!formState.errors.name} />
      </label>
      {formState.errors.name && <p role="alert">{formState.errors.name.message}</p>}

      <label>
        Email
        <input type="email" {...register("email")} aria-invalid={!!formState.errors.email} />
      </label>
      {formState.errors.email && <p role="alert">{formState.errors.email.message}</p>}

      <button type="submit" disabled={formState.isSubmitting}>
        Review
      </button>
    </form>
  );
}

function Review() {
  const stepper = signup.useStepperContext();
  const profile = stepper.data.profile;
  const [error, setError] = useState("");

  async function finish() {
    setError("");
    try {
      await stepper.next();
    } catch {
      setError("Could not save. Try again.");
    }
  }

  return (
    <section>
      <h2>Review</h2>
      <p>
        {profile?.name} · {profile?.email}
      </p>
      {error && <p role="alert">{error}</p>}
      <button type="button" disabled={stepper.isPending} onClick={() => stepper.prev()}>
        Edit
      </button>
      <button type="button" disabled={stepper.isPending} onClick={finish}>
        {stepper.isPending ? "Saving…" : "Finish"}
      </button>
    </section>
  );
}
```

## Why this works [#why-this-works]

- **One provider owns the flow.** Every component below reads it with
  `useStepperContext()`.
- **The form validates the fields; the step validates the move.** Both use
  `profileSchema`. The form shows field errors as it is configured to; the
  step's schema guarantees `next()` cannot leave the step with invalid data,
  whatever called it.
- **`next(values)` saves and moves in one update.** The profile is stored,
  the step becomes complete and the review renders, in a single render.
- **Going back fills the form.** `Edit` calls `prev()`, the form mounts again
  and takes `stepper.data.profile` as its initial values.
- **The request is part of the last move.** `onFinish` returns its promise, so
  `isPending` is `true` while it runs. If it rejects, `next()` rejects, the flow
  is not finished and the person can try again. Once it resolves,
  `stepper.isFinished` is `true` and a second press cannot submit twice.
- **What is sent is the schema's output.** `onFinish` receives what
  `profileSchema` produced, so nothing has to be parsed again.

## Errors that come from the step [#errors-that-come-from-the-step]

When a rule lives only in the step's schema (an async check against the
server, for example), `next()` returns its issues. Hand them to the form so
they show next to their fields:

```tsx
const { handleSubmit, setError } = useForm<Profile>({
  defaultValues: stepper.data.profile ?? { name: "", email: "" },
});

const onSubmit = handleSubmit(async (values) => {
  const result = await stepper.next(values);
  if (result.accepted || !result.issues) return;
  for (const issue of result.issues) {
    const field = issue.path?.[0];
    if (field === "name" || field === "email") setError(field, { message: issue.message });
  }
});
```

Without a `resolver`, the step's schema is the only validation: the form
collects the values and the step judges them.

## Several fields per step, one form for the whole flow [#several-fields-per-step-one-form-for-the-whole-flow]

The example mounts one form per step, which is the simplest setup: each step
owns its fields and hands them over. If you prefer a single `useForm` for the
whole flow, keep it above the steps, validate the fields of the current step
with `trigger`, and pass that step's values to `next`:

```tsx
async function onContinue() {
  const valid = await form.trigger(["name", "email"]);
  if (valid) await stepper.next(form.getValues());
}
```

## Keeping what was typed [#keeping-what-was-typed]

`next(values)` stores the values even when the step's schema rejects them, and
the form reads them back as `defaultValues` when it mounts again. To keep
fields that were never submitted, see
[Keeping steps mounted](https://stepperize.com/docs/v9/react/guides/activity).

Compare with [TanStack Form](https://stepperize.com/docs/v9/react/forms/tanstack-form) and
[Conform](https://stepperize.com/docs/v9/react/forms/conform), or go back to the
[patterns](https://stepperize.com/docs/v9/react/forms/patterns).
