---
title: "Use TanStack Form"
description: "Build a TanStack Form form with our Field parts. Schema checks, server errors, and a submit button that waits."
url: https://gelatinui.com/docs/forms/tanstack-form
markdown_url: https://gelatinui.com/docs/forms/tanstack-form.md
docs_index: https://gelatinui.com/docs/llms.txt
prompt: "Read https://gelatinui.com/docs/forms/tanstack-form.md. Build the form I describe with TanStack Form, a schema, 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 TanStack Form

> Build a TanStack 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 TanStack 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 @tanstack/react-form 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

TanStack Form owns the value and the errors. `Field` shows them. `invalid` turns the field red. `FieldError` with `match` shows the message.

File: `newsletter-form.tsx`.

```tsx
"use client";

import { revalidateLogic, useForm } from "@tanstack/react-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."),
});

export function NewsletterForm() {
  const form = useForm({
    defaultValues: { email: "" },
    validationLogic: revalidateLogic(),
    validators: { onDynamic: newsletterSchema },
    onSubmit: async ({ value }) => {
      await subscribe(value.email);
    },
  });

  return (
    <Form
      onSubmit={(event) => {
        event.preventDefault();
        void form.handleSubmit();
      }}
    >
      <form.Field name="email">
        {(field) => {
          return (
            <Field invalid={!field.state.meta.isValid}>
              <FieldLabel>Email</FieldLabel>
              <Input
                type="text"
                inputMode="email"
                value={field.state.value}
                onValueChange={(value) => {
                  field.handleChange(value);
                }}
                onBlur={field.handleBlur}
              />
              <FieldError match={!field.state.meta.isValid}>
                {field.state.meta.errors[0]?.message}
              </FieldError>
            </Field>
          );
        }}
      </form.Field>
      <div className="flex pt-1">
        <Button type="submit" size="lg">
          Subscribe
        </Button>
      </div>
    </Form>
  );
}
```

## Build a form

Give your schema to `useForm` as one validator. With `revalidateLogic`, 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 { revalidateLogic, useForm } from "@tanstack/react-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."),
});

export function InviteForm() {
  const form = useForm({
    defaultValues: { name: "", email: "" },
    validationLogic: revalidateLogic(),
    validators: {
      onDynamic: inviteSchema,
      onSubmitAsync: async ({ value }) => {
        if (await isMember(value.email)) {
          return { fields: { email: { message: `${value.name} is on the team already.` } } };
        }
        return null;
      },
    },
    onSubmit: async ({ value }) => {
      await invite(value);
    },
  });

  return (
    <Form
      onSubmit={(event) => {
        event.preventDefault();
        if (!form.state.isSubmitting) {
          void form.handleSubmit();
        }
      }}
    >
      <FieldGroup>
        <form.Field name="name">
          {(field) => {
            return (
              <Field invalid={!field.state.meta.isValid}>
                <FieldLabel>Name</FieldLabel>
                <Input
                  value={field.state.value}
                  onValueChange={(value) => {
                    field.handleChange(value);
                  }}
                  onBlur={field.handleBlur}
                />
                <FieldError match={!field.state.meta.isValid}>
                  {field.state.meta.errors[0]?.message}
                </FieldError>
              </Field>
            );
          }}
        </form.Field>
        <form.Field name="email">
          {(field) => {
            return (
              <Field invalid={!field.state.meta.isValid}>
                <FieldLabel>Email</FieldLabel>
                <Input
                  type="text"
                  inputMode="email"
                  value={field.state.value}
                  onValueChange={(value) => {
                    field.handleChange(value);
                  }}
                  onBlur={field.handleBlur}
                />
                <FieldError match={!field.state.meta.isValid}>
                  {field.state.meta.errors[0]?.message}
                </FieldError>
              </Field>
            );
          }}
        </form.Field>
      </FieldGroup>
      <div className="flex pt-1">
        <form.Subscribe
          selector={(state) => {
            return state.isSubmitting;
          }}
        >
          {(isSubmitting) => {
            return (
              <Button type="submit" size="lg" busy={isSubmitting}>
                Send invite
              </Button>
            );
          }}
        </form.Subscribe>
      </div>
    </Form>
  );
}
```

Any Standard Schema works in `validators`: Zod, Valibot, ArkType, or Effect Schema.

## Control types

Every control calls its change callback with the value, not with an event. Pass that value to `field.handleChange(value)` in an arrow function.

| 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 { useForm } from "@tanstack/react-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" };

export function MemberForm() {
  const form = useForm({
    defaultValues: { role: "member", notify: true },
    onSubmit: async ({ value }) => {
      await updateMember(value);
    },
  });

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

## Show the server's errors

Do the server check in `onSubmitAsync`. Return the errors by field name. Each error shows under its field, and `onSubmit` does not run.

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

## Wait for the submit

`form.Subscribe` reads `isSubmitting`. Pass it to the Button `busy` prop. The Button then shows a spinner, keeps its width, and ignores a second press.

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

## Arrays

Set `mode="array"` on a list field. `pushValue` adds a row, and `removeValue` removes a row. Each row is a separate field. Its name uses the index, and its key uses the row id.

File: `emails-form.tsx`.

```tsx
"use client";

import { PlusIcon, XIcon } from "@phosphor-icons/react/ssr";
import { useForm } from "@tanstack/react-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";

export function EmailsForm() {
  const form = useForm({
    defaultValues: {
      emails: [
        { id: "liam", address: "liam@gelatinui.com" },
        { id: "noor", address: "noor@gelatinui.com" },
      ],
    },
    onSubmit: async ({ value }) => {
      await inviteAll(value.emails);
    },
  });

  return (
    <Form
      onSubmit={(event) => {
        event.preventDefault();
        void form.handleSubmit();
      }}
    >
      <form.Field name="emails" mode="array">
        {(list) => {
          return (
            <FieldSet>
              <FieldLegend>Invite by email</FieldLegend>
              {list.state.value.map((row, index) => {
                return (
                  <form.Field key={row.id} name={`emails[${index}].address`}>
                    {(field) => {
                      return (
                        <Field>
                          <InputGroup>
                            <InputGroupInput
                              aria-label={`Email ${index + 1}`}
                              value={field.state.value}
                              onValueChange={(value) => {
                                field.handleChange(value);
                              }}
                            />
                            <InputGroupAddon align="inline-end">
                              <InputGroupButton
                                size="icon-xs"
                                aria-label="Remove email"
                                onClick={() => {
                                  list.removeValue(index);
                                }}
                              >
                                <XIcon aria-hidden />
                              </InputGroupButton>
                            </InputGroupAddon>
                          </InputGroup>
                        </Field>
                      );
                    }}
                  </form.Field>
                );
              })}
              <Button
                variant="outline"
                onClick={() => {
                  list.pushValue({ id: crypto.randomUUID(), address: "" });
                }}
              >
                <PlusIcon aria-hidden data-icon="inline-start" />
                Add email
              </Button>
            </FieldSet>
          );
        }}
      </form.Field>
      <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 TanStack 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 the same test as `invalid` on `Field`.
- **Errors are objects.** A schema gives issue objects, not strings. Show `errors[0]?.message`, not `errors[0]`.
- **One submit at a time.** Two fast Enter presses call `handleSubmit` two times. Return early while `form.state.isSubmitting` is true.

## Next steps

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