---
title: "Use React Hook Form"
description: "Build a React Hook Form form with our Field parts. Schema checks, server errors, and a submit button that waits."
url: https://gelatinui.com/docs/forms/react-hook-form
markdown_url: https://gelatinui.com/docs/forms/react-hook-form.md
docs_index: https://gelatinui.com/docs/llms.txt
prompt: "Read https://gelatinui.com/docs/forms/react-hook-form.md. Build the form I describe with React Hook Form, a schema resolver, and Gelatin UI Field parts. Done: each field shows its error under it, server errors show under their field, and the submit button waits while the request runs."
---

> Docs index: https://gelatinui.com/docs/llms.txt

# Use React Hook Form

> Build a React Hook Form form with our Field parts. Schema checks, server errors, and a submit button that waits.

You get four full files to copy: one field, a full form with server checks, two other control types, and a list of rows. Each file uses React Hook Form for the values and our `Field` parts for the look.

Before you start:

1. Add the items: `npx shadcn@latest add @gelatin-ui/form @gelatin-ui/field @gelatin-ui/button @gelatin-ui/input`. Add the other controls that a file imports (`select`, `switch`, `input-group`) the same way.
2. Add the packages: `npm install react-hook-form @hookform/resolvers zod`. The files use Zod 4.
3. Write the server calls that the files import, or replace them with yours: `subscribe` in `@/lib/newsletter`, and `invite`, `isMember`, `inviteAll`, and `updateMember` in `@/lib/team`. Each takes the form values and returns a promise.

## Anatomy

React Hook Form owns the value and the errors. `Controller` gives them to `Field`. `invalid` turns the field red. `FieldError` with `match` shows the message.

File: `newsletter-form.tsx`.

```tsx
"use client";

import { zodResolver } from "@hookform/resolvers/zod";
import { Controller, useForm } from "react-hook-form";
import { z } from "zod";

import { Button } from "@/components/ui/button";
import { Field, FieldError, FieldLabel } from "@/components/ui/field";
import { Form } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { subscribe } from "@/lib/newsletter";

const newsletterSchema = z.object({
  email: z.email("Enter a full email."),
});

type Newsletter = z.infer<typeof newsletterSchema>;

export function NewsletterForm() {
  const form = useForm<Newsletter>({
    resolver: zodResolver(newsletterSchema),
    defaultValues: { email: "" },
  });

  async function onSubmit(values: Newsletter) {
    await subscribe(values.email);
  }

  return (
    <Form onSubmit={form.handleSubmit(onSubmit)}>
      <Controller
        name="email"
        control={form.control}
        render={({ field, fieldState }) => {
          return (
            <Field invalid={fieldState.invalid}>
              <FieldLabel>Email</FieldLabel>
              <Input
                ref={field.ref}
                type="text"
                inputMode="email"
                value={field.value}
                onValueChange={field.onChange}
                onBlur={field.onBlur}
              />
              <FieldError match={fieldState.invalid}>{fieldState.error?.message}</FieldError>
            </Field>
          );
        }}
      />
      <div className="flex pt-1">
        <Button type="submit" size="lg">
          Subscribe
        </Button>
      </div>
    </Form>
  );
}
```

## Build a form

Pass your schema through `zodResolver`. By default, the form checks on submit first. After that, it checks on each change, so an error goes away when the value is correct.

File: `invite-form.tsx`.

```tsx
"use client";

import { zodResolver } from "@hookform/resolvers/zod";
import { Controller, useForm } from "react-hook-form";
import { z } from "zod";

import { Button } from "@/components/ui/button";
import { Field, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Form } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { invite, isMember } from "@/lib/team";

const inviteSchema = z.object({
  name: z.string().min(1, "Enter a name."),
  email: z.email("Enter a full email."),
});

type Invite = z.infer<typeof inviteSchema>;

export function InviteForm() {
  const form = useForm<Invite>({
    resolver: zodResolver(inviteSchema),
    defaultValues: { name: "", email: "" },
  });

  async function onSubmit(values: Invite) {
    if (await isMember(values.email)) {
      form.setError("email", {
        type: "server",
        message: `${values.name} is on the team already.`,
      });
      return;
    }
    await invite(values);
  }

  return (
    <Form onSubmit={form.handleSubmit(onSubmit)}>
      <FieldGroup>
        <Controller
          name="name"
          control={form.control}
          render={({ field, fieldState }) => {
            return (
              <Field invalid={fieldState.invalid}>
                <FieldLabel>Name</FieldLabel>
                <Input
                  ref={field.ref}
                  value={field.value}
                  onValueChange={field.onChange}
                  onBlur={field.onBlur}
                />
                <FieldError match={fieldState.invalid}>{fieldState.error?.message}</FieldError>
              </Field>
            );
          }}
        />
        <Controller
          name="email"
          control={form.control}
          render={({ field, fieldState }) => {
            return (
              <Field invalid={fieldState.invalid}>
                <FieldLabel>Email</FieldLabel>
                <Input
                  ref={field.ref}
                  type="text"
                  inputMode="email"
                  value={field.value}
                  onValueChange={field.onChange}
                  onBlur={field.onBlur}
                />
                <FieldError match={fieldState.invalid}>{fieldState.error?.message}</FieldError>
              </Field>
            );
          }}
        />
      </FieldGroup>
      <div className="flex pt-1">
        <Button type="submit" size="lg" busy={form.formState.isSubmitting}>
          Send invite
        </Button>
      </div>
    </Form>
  );
}
```

`zodResolver` comes from `@hookform/resolvers`. That package also has resolvers for Valibot, ArkType, and Standard Schema.

## Control types

Every control calls its change callback with the value, not with an event. So you can pass `field.onChange` from `Controller` directly, with no wrapper.

| Controls                                                                                             | Value     | On change         |
| ---------------------------------------------------------------------------------------------------- | --------- | ----------------- |
| Input, Textarea, Select, Combobox, Radio Group, Checkbox Group, Number Field, Date Picker, Input OTP | `value`   | `onValueChange`   |
| Checkbox, Switch                                                                                     | `checked` | `onCheckedChange` |

File: `member-form.tsx`. It shows a Select and a Switch.

```tsx
"use client";

import { Controller, useForm } from "react-hook-form";

import { Button } from "@/components/ui/button";
import { Field, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Form } from "@/components/ui/form";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectLabel,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import { updateMember } from "@/lib/team";

const roles = { member: "Member", admin: "Admin", billing: "Billing" };

type Member = { role: string; notify: boolean };

export function MemberForm() {
  const form = useForm<Member>({
    defaultValues: { role: "member", notify: true },
  });

  return (
    <Form onSubmit={form.handleSubmit(updateMember)}>
      <FieldGroup>
        <Controller
          name="role"
          control={form.control}
          render={({ field }) => {
            return (
              <Field>
                <Select items={roles} value={field.value} onValueChange={field.onChange}>
                  <SelectLabel>Role</SelectLabel>
                  <SelectTrigger ref={field.ref} onBlur={field.onBlur}>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {Object.entries(roles).map(([value, label]) => {
                      return (
                        <SelectItem key={value} value={value}>
                          {label}
                        </SelectItem>
                      );
                    })}
                  </SelectContent>
                </Select>
              </Field>
            );
          }}
        />
        <Controller
          name="notify"
          control={form.control}
          render={({ field }) => {
            return (
              <Field>
                <FieldLabel>
                  <Switch checked={field.value} onCheckedChange={field.onChange} />
                  Email me when my role changes
                </FieldLabel>
              </Field>
            );
          }}
        />
      </FieldGroup>
      <div className="flex pt-1">
        <Button type="submit" size="lg">
          Save
        </Button>
      </div>
    </Form>
  );
}
```

## Show the server's errors

Call `setError` after the request. The error shows under its field. It goes away when the person changes the value.

See `setError` in `invite-form.tsx`, in [Build a form](#build-a-form).

## Wait for the submit

`formState.isSubmitting` stays true while `onSubmit` runs. Pass it to the Button `busy` prop. The Button then shows a spinner, keeps its width, and ignores a second press.

See `isSubmitting` in `invite-form.tsx`, in [Build a form](#build-a-form).

## Arrays

`useFieldArray` gives the rows and two actions. `append` adds a row, and `remove` removes a row. Each row is an object with its own `id`.

File: `emails-form.tsx`.

```tsx
"use client";

import { PlusIcon, XIcon } from "@phosphor-icons/react/ssr";
import { Controller, useFieldArray, useForm } from "react-hook-form";

import { Button } from "@/components/ui/button";
import { Field, FieldLegend, FieldSet } from "@/components/ui/field";
import { Form } from "@/components/ui/form";
import {
  InputGroup,
  InputGroupAddon,
  InputGroupButton,
  InputGroupInput,
} from "@/components/ui/input-group";
import { inviteAll } from "@/lib/team";

type Emails = { emails: { address: string }[] };

export function EmailsForm() {
  const form = useForm<Emails>({
    defaultValues: {
      emails: [{ address: "liam@gelatinui.com" }, { address: "noor@gelatinui.com" }],
    },
  });
  const { fields, append, remove } = useFieldArray({
    control: form.control,
    name: "emails",
  });

  return (
    <Form
      onSubmit={form.handleSubmit((values) => {
        return inviteAll(values.emails);
      })}
    >
      <FieldSet>
        <FieldLegend>Invite by email</FieldLegend>
        {fields.map((row, index) => {
          return (
            <Controller
              key={row.id}
              name={`emails.${index}.address`}
              control={form.control}
              render={({ field }) => {
                return (
                  <Field>
                    <InputGroup>
                      <InputGroupInput
                        ref={field.ref}
                        aria-label={`Email ${index + 1}`}
                        value={field.value}
                        onValueChange={field.onChange}
                      />
                      <InputGroupAddon align="inline-end">
                        <InputGroupButton
                          size="icon-xs"
                          aria-label="Remove email"
                          onClick={() => {
                            remove(index);
                          }}
                        >
                          <XIcon aria-hidden />
                        </InputGroupButton>
                      </InputGroupAddon>
                    </InputGroup>
                  </Field>
                );
              }}
            />
          );
        })}
        <Button
          variant="outline"
          onClick={() => {
            append({ address: "" });
          }}
        >
          <PlusIcon aria-hidden data-icon="inline-start" />
          Add email
        </Button>
      </FieldSet>
      <div className="flex pt-1">
        <Button type="submit" size="lg">
          Send invites
        </Button>
      </div>
    </Form>
  );
}
```

## Traps

Our own sign-in and settings forms had these bugs first. Each trap has its fix.

- **Two checks fight.** `Form` runs the browser checks before `onSubmit`. With `type="email"`, a bad email stops the submit, so React Hook Form never runs. Use `type="text"` with `inputMode="email"`, and let the schema check the value.
- **FieldError needs match.** With no `match`, `FieldError` shows only the browser checks. Give it `fieldState.invalid`, the same value as `invalid` on `Field`.
- **Key rows by id.** Use `row.id` from `useFieldArray` as the key. With an index key, the values move to the wrong rows when you remove a row in the middle.
- **Await the request.** `isSubmitting` stays true only while the promise of `onSubmit` runs. Await the request, or the Button stops waiting at once.

## Next steps

- [Use TanStack Form](https://gelatinui.com/docs/forms/tanstack-form.md): the same forms with TanStack Form.
- [Field](https://gelatinui.com/components/field.md): every part and prop of Field.
