# Forms

> Progressive forms, pending state and validation errors.

`<Form>` submits to a server action and handles the state around it: pending,
validation errors, success and optimistic updates. It works before the page's
JavaScript has loaded.

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

import { Form } from "@rsc-kit/core/form";
import * as orders from "../server-actions/orders";

export function NewOrder() {
  return (
    <Form action={orders.create}>
      {({ pending, error }) => (
        <>
          <input name="title" />
          {error('title') && <p>{error('title')}</p>}
          <button disabled={pending}>{pending ? 'Saving…' : 'Save'}</button>
        </>
      )}
    </Form>
  );
}
```

## Submitting a form

Pass a server action as `action`. The children are a function that receives the
form's state:

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

import { Form } from "@rsc-kit/core/form";
import { addTodo } from "./actions";

type FormValues = { title: string };

export default function TodoForm() {
  return (
    <Form<FormValues> action={addTodo}>
      {({ pending, error }) => (
        <>
          <input name="title" placeholder="What needs to be done?" />
          {error('title') && <span className="text-red-500">{error('title')}</span>}
          <button disabled={pending}>{pending ? 'Adding...' : 'Add Todo'}</button>
        </>
      )}
    </Form>
  );
}
```

The inputs are ordinary named inputs. They keep their own value, and the action
reads them as `FormData` on submit. There's no `useState` per field and no
`value`/`onChange` pair, and typing doesn't re-render the form. Bind a field
only when the page has to react as it's typed: see
[controlling one field](#controlling-one-field).

The type parameter, `<FormValues>`, types the names `error()` accepts. With a
generated action you don't need it: the names come from the action.

What the render function receives:

| Name | What it is |
| --- | --- |
| `error(name)` | The field's message, or `undefined`. |
| `formError` | A refusal that isn't about one field. |
| `field(name)` | A binding to spread onto a control you need to hold. |
| `pending` | `true` while the submit is running. |
| `dirty` | Whether any value differs from what the form started with. |
| `succeeded`, `recentlySucceeded` | Whether the last submit succeeded; the second for two seconds only. |
| `reset()`, `clearErrors()` | Go back to the starting values; clear the errors. |
| `validate()`, `validating`, `valid(name)` | Ask the server to check fields now. |

### Form props

| Prop | What it does |
| --- | --- |
| `action` | A server action (POST), or a URL (GET). |
| `method` | `"get"` or `"post"`. Defaults to `"post"` for an action and `"get"` for a URL. |
| `schema` | A schema to check the values with in the browser. |
| `defaultValues` | Starting values for bound fields. |
| `fields` | Field names, for a form whose values aren't posted fields. |
| `resetOnSuccess` | Reset the form after a successful submit. Default `true`. |
| `optimistic` | Called inside the transition, for [optimistic updates](#optimistic-updates). |
| `onSuccess` | Called with the action's result. Not after a redirect, unless it [came back to this page](/guides/redirects#back-to-the-same-page). |
| `onError` | Called with the validation errors on a 422. |
| `onSubmit` | Called before submitting. Return `false` to cancel. |
| `prefetch` | `"hover"` (default), `"mount"` or `"none"`. GET forms only. |
| `replace` | Replace the history entry. GET forms only. |
| `preserveScroll` | Keep the scroll position. GET forms only: an action that redirects back to the page it was posted from always keeps it. |

### In a component of its own

`useForm()` returns what the render function receives, so part of a form can
move into its own component:

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

import { useForm } from "@rsc-kit/core/form";

export function SubmitButton() {
  const { pending } = useForm();

  return (
    <button type="submit" disabled={pending}>
      {pending ? 'Saving...' : 'Save'}
    </button>
  );
}
```

This isn't React's `useFormStatus`, which is a different hook with a different
answer.

## Validation errors

When a submit fails validation, `error('title')` returns the field's message.
There's no `try`/`catch` to write and no state to hold.

```tsx
{error('title') && <p>{error('title')}</p>}
{error('address.city')}      {/* a nested field */}
{error('items[0].name')}     {/* a field in a list */}
{formError && <p role="alert">{formError}</p>}
```

- **`error(name)`** shows a field's message. `!!error('title')` tells you
  whether the field is invalid.
- **`formError`** is a refusal that isn't about one field: the action's
  `serverError`, such as a payment required or a slot just taken, or a message
  for the whole form. It clears with the field errors.
- A failure on the way, such as the network, goes to `onError` instead.

Errors come from the schema in the browser and from the server, and `error()`
shows both. Where the server's come from depends on your backend: see
[Validation](/guides/validation).

### Returning an error from an action

An action can refuse a field itself, for something no schema could know.
Return `fieldErrors()`:

```ts
'use server';

import { fieldErrors } from '@rsc-kit/core/action';

export async function addTodo(formData: FormData) {
  const title = String(formData.get('title'));

  if (await exists(title)) return fieldErrors({ title: 'Already on the list' });

  await save(title);
}
```

The form shows it under that field, the same as a schema failure. Through the
[action client](/guides/server-actions#failing-on-something-a-schema-cannot-know),
`fieldErrors` arrives with the handler's arguments, typed to its input.

## Field names

`error()` and `clearErrors()` are typed from the action's input, so a typo fails
the typecheck instead of never matching:

```tsx
<Form action={orders.create}>
  {({ error }) => (
    <>
      {error('name')}          {/* ok */}
      {error('address.city')}  {/* ok: a nested path */}
      {error('items.0.sku')}   {/* ok: a list's index */}
      {error('nmae')}          {/* type error */}
    </>
  )}
</Form>
```

The names come from:

- a generated action's parameter. The backend lists the fields of the struct or
  form request it takes in `rsc-host.json`, so you write nothing.
- `createActionClient()`'s `.input(schema)`.
- `defaultValues` on the form.

When the action says nothing about its input - a function of `FormData`, a URL,
a cast - any name is accepted. A name the backend reports that its input
doesn't have, such as a key it computes, is a type error: add it to
`defaultValues`.

### Typing a wrapper around an action

A function of `FormData` could read anything, so it names no fields. Declare
them on its parameter with `FormFields`:

```tsx
import type { FormFields } from '@rsc-kit/core/form'
import * as apps from './server-actions/apps'

export async function renameApp(form: FormFields<'id' | 'name'>) {
  'use server'
  await apps.rename(String(form.get('id')), String(form.get('name')))
}
```

`<Form action={renameApp}>` then accepts `error('id')` and `error('name')`, plus
whatever `defaultValues` adds. A `FormFields` is a `FormData`: the names are
types only, and nothing is checked in the browser. Include a field the backend
may refuse that the form doesn't post, such as `redirect`.

### Binding an argument first

For an action like `func(ctx, team string, in NewApp)`, bind the team and the
form fills the struct after it. Bind into a `const` first:

```tsx
const create = apps.create.bind(null, team) // once, not inline

<Form action={create}>{({ error }) => error('name')}</Form>
```

Written inline in the JSX, TypeScript loses the names: the form compiles, but
accepts any name. An action whose parameters are all plain strings has no
struct for a form to fill, so wrap it as above.

### A form that posts nothing

When the values live in React state, or the form is a single button, name the
fields on the form:

```tsx
<Form action={resize} fields={['size', 'copies']}>
  {({ error }) => error('size')}  {/* error('sise') fails the typecheck */}
</Form>
```

`fields` adds to the action's own names and `defaultValues`. It is types only.
It also names a field the backend reports under a different spelling, such as
an untagged Go field `Host` reported as `host`, though tagging the struct
(`json:"host"`) is the cleaner fix.

A component below the form types its prop with `FieldNamesOf`:

```tsx
import type { FieldNamesOf } from '@rsc-kit/core/form'

type Props = { name: FieldNamesOf<typeof orders.create> }
```

## Setting the values

An initial value is React's own `defaultValue`:

```tsx
<Input id="title" name="title" defaultValue={post.title} />
```

After a refused submit the values are still there, because nothing re-rendered
the inputs.

The exception is a submit made before the page's JavaScript loaded, which
reloads the page. The server renders the page again, so return the values from
the action and render them as `defaultValue`.

## How the values are read

Write the schema for the values you want, not for the strings a form posts:

```ts
const settings = z.object({
  notify: z.boolean(),                 // unchecked posts nothing → false; "on" → true
  limit: z.number().int().min(1),      // "5" → 5
  tags: z.array(z.string()),           // one tag → ['a']; none ticked → []
  policy: z.string().optional(),       // hidden behind a switch → absent when off
  auth: z.discriminatedUnion('kind', [ // auth[kind] picks the branch
    z.object({ kind: z.literal('none') }),
    z.object({ kind: z.literal('bearer'), token: z.string().min(1) }),
  ]),
  rules: z.array(z.object({ on: z.boolean(), max: z.number() })),  // rules[0][on], rules[0][max]
}).refine((s) => !s.notify || (s.policy ?? '').length > 0, {
  path: ['policy'],
  message: 'Say what to notify about.',
})
```

No `z.coerce.number()` and no `.transform()` per checkbox. The form is read the
way the schema describes it, in the browser and again in the action:

- A `boolean` that is absent is `false`. `"on"` or `"1"` is `true`.
- A numeric string for a `number` is the number. An empty one for an optional
  number is absent.
- An `array` given one value is a list of one, and given nothing is empty.
- Nested names nest: `fields[0][name]` and `fields[0].name` alike.
- A union takes the branch its discriminator names.
- A blank control is absent for a field the schema doesn't require, so
  `z.email().optional()` accepts an empty input. It is `""` for a field the
  schema requires, so `z.string().min(1)` can refuse it.
- A value the schema refuses is refused as it was posted: `"many"` for a number
  is the error you expect.

This needs a schema that describes itself (Standard JSON Schema). Zod 4 and
ArkType do. Valibot doesn't yet, and its values arrive as strings. A part the
JSON Schema can't describe, such as `z.date()` or a custom check, arrives as
posted, and the rest of the form is still read normally. A schema that can't
describe itself at all is reported once in development, with the library's
reason.

A value sent through `<Form transform>` is encoded the same way back, a boolean
as `"1"`/`"0"` and a nested object as `key[prop]`, and decodes to what was
given.

### Lists of values

A repeated name is an array:

```tsx
<Checkbox name="tags" value="react" />
<Checkbox name="tags" value="vite" />
// → { tags: ['react', 'vite'] }
```

With only one ticked, that is the string `'react'`, which `z.array()` refuses.
End the name in `[]` and it is always an array:

```tsx
<Checkbox name="tags[]" value="react" />
// → { tags: ['react'] }
```

The brackets are dropped from the key, and a value is written back the same
way, so a list survives a round trip.

### Nested and repeating groups

Names that describe a shape build it:

```tsx
<input name="address.city" />                 // → { address: { city } }
<input name="items[0].name" />                // → { items: [{ name }] }
<input name="items[0][name]" />               // the same field, other spelling
```

Errors come back under the same paths: a refused `address.city` is
`error('address.city')`.

Rows you add and remove are ordinary state. Only the names have to line up:

```tsx
{rows.map((row, i) => (
  <input key={row.id} name={`items[${i}].name`} defaultValue={row.name} />
))}
```

## When fields are checked

**A field is checked when it is left, not as it is typed**, and when the form is
submitted. So `error()` has nothing for a field nobody has reached yet, and
there's no separate "touched" state to check.

The form listens for `focusout` itself, so a plain `<Input name="title" />` is
covered without binding it.

### Checking with the server before submit

Add `precognitive` and, when a field is left **having changed**, the form asks
the server to check it:

```tsx
<Form action={register} precognitive>
```

The action's guards and validation run for that field, and the action itself
doesn't. The answer shows on `error()` like any other. This catches what a
schema in the browser can't know, such as an email that is already subscribed
or a coupon that has expired.

Without `precognitive`, the server hears from the form only when it is
submitted, or when you call `validate()`. A `schema` still checks each field as
it is left, since that runs in the browser.

The actions that can be asked:

- a `createActionClient()` action with an input schema. Its middleware and
  schema run, and its handler is skipped.
- a backend function the backend can check without running it. In Laravel,
  that is any action whose first parameter is a form request: its
  `authorize()` and `rules()` run, filtered to the field, as Laravel's
  Precognition does.
- nothing else. A plain `"use server"` function can't be stopped before its
  body, so it is never called to check, and the form stops asking after the
  first answer says so.

A field the browser's schema already refuses isn't sent. A field left without
being changed isn't asked about again. A field left for the form's own submit
button isn't asked about either: the submit checks every field. A file is sent
only when its own field is the one being checked.

A check runs the action's guards, so a check counts against a `throttle` on
the action as a submit does. A form of four fields behind a limit of five spends
the limit before it is sent. Let checks through in the limiter: on Laravel,
`$request->isPrecognitive()` is true for a check while the guards run (see
[Checking a field as it is filled in](/hosts/laravel/server-actions/#checking-a-field-as-it-is-filled-in)).

#### When a blur is not the moment

`validate()` asks now, about the fields you name, or every field with none. It
resolves `true` when they pass. Use it for a wizard's steps:

```tsx
<Form action={register}>
  {({ validate, validating, valid, error }) => (
    <>
      {step === 1 && (
        <>
          <Input name="email" />
          {valid('email') && <Check />}
          {error('email') && <p>{error('email')}</p>}
          <Button
            type="button"
            disabled={validating}
            onClick={async () => (await validate('email', 'name')) && setStep(2)}
          >
            Next
          </Button>
        </>
      )}
      {/* ... */}
    </>
  )}
</Form>
```

Keep each step's fields in the form while hidden (render them with `hidden`, not
conditionally), so the last step's submit sends every one.

- `*` stands for one segment of a nested name, as in Laravel:
  `validate('items.*.sku')`.
- To check a field as it is typed, call `validate('handle')` from its
  `onChange`, and debounce it yourself.
- `validating` is `true` while a check is out.
- `valid(name)` is `true` once a check of that field passed and it hasn't been
  edited since. Use it for a tick beside the field, not for deciding anything.

## After a successful submit

```tsx
{({ succeeded, recentlySucceeded }) => (
  <Button type="submit">{recentlySucceeded ? 'Saved ✓' : 'Save'}</Button>
)}
```

`recentlySucceeded` is `succeeded` for two seconds only, for a tick that
appears and fades. The form clears the timer when the component goes away.

## Disabling save until something changes

```tsx
{({ dirty, reset }) => (
  <>
    <Button type="submit" disabled={!dirty}>Save</Button>
    {dirty && <Button type="button" variant="ghost" onClick={reset}>Discard</Button>}
  </>
)}
```

`dirty` is whether any value differs from what the form started with,
uncontrolled fields included. A successful submit makes the current values the
new starting point, and `reset()` goes back to the first one.

A form only measures `dirty` when something reads it, and it renders once when
the value first differs, not on every keystroke after.

## Controlling one field

Bind a field with `field(name)` when it has no native element behind it, or
when you want to show its value as it's typed:

```tsx
<Form action={reportBug} schema={formSchema} defaultValues={{ description: '' }}>
  {({ field, error }) => (
    <Field data-invalid={!!error('description')}>
      <FieldLabel htmlFor="description">Description</FieldLabel>

      <InputGroup>
        <InputGroupTextarea id="description" {...field('description')} rows={6} />
        <InputGroupAddon align="block-end">
          <InputGroupText>{field('description').value.length}/100 characters</InputGroupText>
        </InputGroupAddon>
      </InputGroup>

      <FieldError>{error('description')}</FieldError>
    </Field>
  )}
</Form>
```

`field()` returns `{ name, value, onChange, onBlur }`, like react-hook-form's
`<Controller>`. `onChange` takes a DOM event or a bare value, so a native input
and a Base UI or Radix `Select` both work without a wrapper. A bound field is
still a named input, so it is submitted with everything else.

Bind only the fields that need it and leave the rest alone.

### In its own component

`field()` re-renders the component holding the form. When a form is large, put
the field in its own component with `useField`, which re-renders that component
and nothing else:

```tsx
import { useField } from '@rsc-kit/core/form'

function Title() {
  const { field, error } = useField('title')

  return <Input {...field} aria-invalid={!!error} />
}
```

### Reading a value from elsewhere

A preview, a summary or a count reads a value the same way:

```tsx
function Preview() {
  const { field } = useField('title')

  return <h2>{field.value || 'Untitled'}</h2>
}
```

Only a bound field can be read this way. An uncontrolled input's value is in
the DOM, so bind it with `field()` or `useField` first.

`useForm()` and `useField()` work anywhere below `<Form>`. A submit button
outside the `<form>` element can use `form="the-id"`. For a component that isn't
below the form at all, create the store yourself and pass it to both:

```tsx
function Page() {
  const store = useFormStore<{ title: string }>({ title: '' })

  return (
    <>
      <TopBar store={store} />          {/* not inside the form */}
      <Form action={save} store={store}>…</Form>
    </>
  )
}

function TopBar({ store }) {
  const { field } = useField('title', store)

  return <h1>{field.value || 'Untitled'}</h1>
}
```

`useFormStore` holds the values only: no submit, no errors. Creating it doesn't
subscribe to it, so the component holding it doesn't re-render on every
keystroke.

## Optimistic updates

Pass `optimistic` and update React's `useOptimistic` state in it. It runs
inside the transition, so React reverts it if the action fails:

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

import { useOptimistic } from "react";
import { Form } from "@rsc-kit/core/form";
import { addTodo } from "./actions";

type Todo = { id: number; title: string; done: boolean };

export default function TodoList({ todos }: { todos: Todo[] }) {
  const [optimisticTodos, addOptimistic] = useOptimistic(
    todos,
    (state, newTodo: Todo) => [...state, newTodo]
  );

  return (
    <div>
      <ul>
        {optimisticTodos.map((todo) => (
          <li key={todo.id}>{todo.title}</li>
        ))}
      </ul>

      <Form
        action={addTodo}
        optimistic={(data) =>
          addOptimistic({ id: Date.now(), title: data.title as string, done: false })
        }
      >
        <input name="title" />
        <button>Add</button>
      </Form>
    </div>
  );
}
```

## Stopping bots

Put `<Honeypot />` inside the form:

```tsx
import { Form } from '@rsc-kit/core/form'
import { Honeypot } from '@rsc-kit/core/honeypot'

<Form action={subscribe}>
  <input name="email" type="email" />
  <Honeypot />
  <button>Subscribe</button>
</Form>
```

It renders a field people never see. It is off screen, out of the tab order,
hidden from screen readers and not autofilled. A bot that fills in every input
fills that one too. Its post is answered as though it worked and dropped before
the action runs, so the action never sees it and the bot learns nothing.

- It works in any form that posts to a server action: `<Form>`, a plain
  `<form action={…}>`, with JavaScript or without, and for a `"use server"`
  function or a Laravel or Go action. The check happens in the renderer,
  before the call reaches the backend.
- The trap is taken out of the form either way, so the action sees only the
  fields a person filled in.
- The field is named `homepage`. `<Honeypot name="website" />` picks another
  name, if the form has a real field called `homepage`. Forms without
  `<Honeypot />` are not checked, so a `homepage` field elsewhere is ordinary.

It stops the crudest spam, not a determined attacker. A form worth attacking
wants a rate limit on its action as well, such as Laravel's `throttle`
middleware on the action class. [Blueprints](/guides/blueprints/#stopping-bots)
show it, and [protecting a server action](/guides/authorization/#protect-a-server-action)
covers guarding one written in JavaScript.

## Search and filter forms

When `action` is a URL, the form navigates to it with the fields as the query
string, without a full page reload:

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

import { Form } from "@rsc-kit/core/form";

export default function SearchForm() {
  return (
    <Form action="/search" method="get" prefetch="hover">
      <input name="q" placeholder="Search..." />
      <select name="sort">
        <option value="relevance">Relevance</option>
        <option value="date">Date</option>
      </select>
      <button>Search</button>
    </Form>
  );
}
```

This goes to `/search?q=hello&sort=date`, and the nearest Suspense boundary
streams in the results. With `prefetch="hover"`, hovering the submit button
starts loading the page.

### A search on the page it is on

When the form's `action` is the page the visitor is on, the page stays on
screen while the query runs, and the new results replace the old ones when
they arrive. The input keeps what was typed, a Suspense boundary already
showing content keeps showing it, and Back returns to the previous query.

`pending` stays `true` until the new results are on screen:

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

import { Form } from "@rsc-kit/core/form";

export default function Lookup() {
  return (
    <Form action="/lookup" method="get">
      {({ pending }) => (
        <>
          <input name="q" />
          <button disabled={pending}>{pending ? "Searching…" : "Search"}</button>
        </>
      )}
    </Form>
  );
}
```

To show a skeleton instead of the old results, style them from the form's
`data-pending` attribute. The results can stay outside the form, with no client
component for them:

```css
#results-skeleton { display: none }
section:has(form[data-pending]) #results { display: none }
section:has(form[data-pending]) #results-skeleton { display: block }
```

Only a `<Form>` does this. A `<Link>` or `visit()` to the same path with another
query loads it as a new page. The form doesn't prefetch the page it is already
on.

## Using it with shadcn/ui

shadcn's inputs work as they are, because `<Form>` reads the form's native
`FormData`:

```tsx
<Form action={createPost} schema={schema}>
  {({ pending, error }) => (
    <>
      <Label htmlFor="title">Title</Label>
      <Input id="title" name="title" />
      {error('title') && <p className="text-destructive">{error('title')}</p>}

      <Select name="kind">
        <SelectTrigger><SelectValue /></SelectTrigger>
        <SelectContent>
          <SelectItem value="post">Post</SelectItem>
        </SelectContent>
      </Select>

      <Checkbox name="draft" />

      <Button disabled={pending}>{pending ? 'Saving…' : 'Save'}</Button>
    </>
  )}
</Form>
```

- `Input`, `Textarea`, `Button` and `Label` are styled native elements.
- **`Select`, `Checkbox`, `Switch` and `RadioGroup` also work**, on Base UI or
  Radix. Each renders a hidden native control when you give it a `name`. Without
  a `name`, the form can't see it.
- A pick in a Base UI `Select` changes its hidden control without firing an
  event. `<Form>` watches its own controls, so `dirty` and `valid()` still see
  the change.

:::caution[Not shadcn's own `<Form>`]
shadcn's `<Form>`, `<FormField>` and `<FormControl>` wrap
[react-hook-form](https://react-hook-form.com), which has its own state,
validation and submit. Use one or the other, not both.
:::

### shadcn's `Field` components

`Field`, `FieldLabel`, `FieldError` and `FieldGroup` take props rather than
reading a form library's context, so they work directly:

```tsx
<Form action={reportBug} schema={formSchema}>
  {({ pending, error }) => (
    <FieldGroup>
      <Field data-invalid={!!error('title')}>
        <FieldLabel htmlFor="title">Bug title</FieldLabel>
        <Input id="title" name="title" aria-invalid={!!error('title')} />
        <FieldDescription>Keep it short and specific.</FieldDescription>
        <FieldError>{error('title')}</FieldError>
      </Field>

      <Button type="submit" disabled={pending}>
        {pending ? 'Sending…' : 'Submit'}
      </Button>
    </FieldGroup>
  )}
</Form>
```

`FieldError` renders nothing when it has no children, so `error('title')` goes
straight in. Unlike with a client-side form library, `error()` includes the
errors the server sent back.

## It works before hydration

A form can be submitted before the page's JavaScript has loaded. The browser
posts it, and the page reloads with the result instead of updating in place.
There is nothing to turn on.

- The action runs as it would have otherwise, and a refusal shows on its
  fields, `error('email')` included, for a visitor with no JavaScript at all.
- A `redirect()` from the action is followed, and a cookie it sets is kept.
- It is same origin only, as an action is, and the answer is never stored.

A stored page is the one most likely to be submitted this way, since it shows
before its JavaScript arrives. It is also why fields are real `name` attributes
rather than state: the browser can read them without help.

`<Form>` uses React's `useActionState` for this, and your action still takes
the `FormData` alone. A `useActionState` of your own works too, with an action
written for `(previousState, formData)`. Once the page has hydrated, the form
cancels the native submit and handles it itself.

## Coming from react-hook-form or TanStack Form

The default is react-hook-form's: fields are uncontrolled, and typing
re-renders nothing. TanStack Form is controlled-first, so it is the opposite.

| | react-hook-form | Here |
| --- | --- | --- |
| A plain field | `register('title')` | `name="title"` |
| A controlled field | `<Controller render={…}>` | `field('title')` |
| A field that re-renders alone | `<Controller>` | `useField('title')` in its own component |
| Reaching the form from below | `useFormContext()` | `useForm()` |
| State created above the form | `useForm()` | `useFormStore()` |
| Errors from the server | written by hand | `error()`, with the browser's |
