Skip to content

React Hook Form

@beignet/react-hook-form creates typed React Hook Form options from a contract body schema. Use it when a form submits to a contract and should reuse the same validation rules on the client.

Follow Connect forms and lists to use the starter's Todos API in a complete screen with validation, pagination, cache refreshes, and request-error recovery.

bash
bun add @beignet/react-hook-form react-hook-form@^7.55.0 @hookform/resolvers@^7.0.1

Beignet supports @hookform/resolvers v5, v6, and v7 with React Hook Form 7.55.0 or newer within v7. New starters use resolver v7; existing v5 and v6 installs remain supported. Beignet uses the Standard Schema resolver, so these upgrades do not change parsed submissions, raw mode, or form options. Custom resolvers follow their integration's migration requirements: v6 requires Effect v4 for effectTsResolver, and v7 moves TypeBox to typebox 1.x instead of @sinclair/typebox, with new error types and messages.

React Hook Form only owns the request body fields. Path params, query params, required headers, idempotency keys, and auth context still belong to the endpoint call. Forms submit parsed values by default. Reuse the contract body schema for ordinary forms, or pass rhf(contract, { schema }) when UI values need conversion into the request body. The selected form schema must have object-shaped input for named fields; its output can be a scalar or array.

Setup

Use the Todos contracts from Quickstart. The starter already installs the form packages, exports rhf from client/forms.ts, and mounts the React Query provider. Sign in before submitting the form.

Add the feature binding:

typescript
// features/todos/client/forms.ts
import { rhf } from "@/client/forms";
import { createTodo } from "@/features/todos/contracts";

export const createTodoForm = rhf(createTodo);

Outside the starter, create rhf once with createReactHookForm() from @beignet/react-hook-form. Bind the contract directly with rhf(contract); contract.config is only needed by integrations that cannot accept the builder.

Basic form

Add this component and render <CreateTodoForm /> on a signed-in page under the existing Query Client provider:

tsx
// features/todos/components/create-todo-form.tsx
"use client";

import { rootFormError } from "@beignet/react-hook-form";
import { useMutation } from "@tanstack/react-query";
import { useId } from "react";
import { rq } from "@/client";
import { createTodoForm } from "@/features/todos/client/forms";
import { createTodo, listTodos } from "@/features/todos/contracts";

export function CreateTodoForm() {
  const titleId = useId();
  const form = createTodoForm.useForm({ defaultValues: { title: "" } });
  const mutation = useMutation(
    rq(createTodo).mutationOptions({
      invalidates: () => [rq(listTodos).contractFilter()],
      onSuccess: () => form.reset(),
      onError: (error) => {
        form.setError("root", rootFormError(error, "Could not create the todo."));
      },
    }),
  );
  const onSubmit = form.handleSubmit((body) => {
    form.clearErrors("root");
    mutation.mutate({ body });
  });

  return (
    <form onSubmit={onSubmit}>
      <label htmlFor={titleId}>Title</label>
      <input
        id={titleId}
        {...form.register("title")}
        readOnly={mutation.isPending}
        aria-invalid={!!form.formState.errors.title}
        aria-describedby={
          form.formState.errors.title ? `${titleId}-error` : undefined
        }
      />
      {form.formState.errors.title && (
        <p id={`${titleId}-error`} role="alert">
          {form.formState.errors.title.message}
        </p>
      )}
      {form.formState.errors.root && (
        <p role="alert">{form.formState.errors.root.message}</p>
      )}
      <button type="submit" disabled={mutation.isPending}>
        {mutation.isPending ? "Creating…" : "Create"}
      </button>
    </form>
  );
}

Submit an empty title: the contract's body schema rejects it before a request is sent. Submit a valid title: the API saves it, the form resets, and mounted Todos queries refresh. If the request fails, the form keeps the title and shows an error. The fields stay read-only until the mutation and its invalidation work finish.

With React Query

invalidates above targets every cached call to listTodos. Active queries refetch; inactive queries become stale. See React Query mutations for the lifecycle and cache-refresh behavior.

rootFormError(error, fallback, overrides?) wraps contractErrorMessage from @beignet/core/client into the form.setError("root", ...) shape. Non-contract errors get the fallback copy, and catalog codes can override copy per form. See Errors.

beignet make feature <name> --with ui generates form binding, mutation handling, errors, success reset, and list invalidation. The full-slice recipe includes the same UI addon. Build your first feature walks through a complete Projects form with ownership checks and tests.

Input and output types

Live field values — register, watch, setValue, getValues, and defaultValues — use the selected schema's input type. handleSubmit receives its parsed output by default, including transforms, defaults, and removal of unknown keys. Invalid values produce field errors and prevent submission. Parsing does not replace live field state. Use defaultValues for defaults that should appear in the form itself.

The form prepares request data, the typed client sends that data unchanged, and the server independently validates the request. Keep HTTP contracts shaped around the data the API accepts. If the API accepts a number, use z.number() and convert the UI value before calling the typed client.

Numeric fields

A numeric field can produce a number before schema validation, so the form and contract can reuse the same schema. This standalone payment contract illustrates that boundary:

typescript
import { defineContract } from "@beignet/core/contracts";
import { z } from "zod";

const paymentBody = z.object({
  amount: z.number().int().positive(),
  currency: z.string().default("USD"),
});
const createPayment = defineContract({ method: "POST", path: "/api/payments" })
  .body(paymentBody)
  .responses({ 201: z.object({ id: z.string() }) });

const form = rhf(createPayment).useForm({
  defaultValues: { amount: 0, currency: "USD" },
});
tsx
<input type="number" {...form.register("amount", { valueAsNumber: true })} />

z.number() validates numbers; it does not convert strings. Use z.coerce.number() in a shared contract only when the API intentionally accepts numeric strings too. Its input type is unknown by default; an explicit z.coerce.number<string | number>() narrows TypeScript callers without changing runtime coercion.

A separate form schema

When the form edits a different representation, pass a form schema at binding time. Its input defines the fields, and its parsed output must be assignable to the contract body's input type:

typescript
const paymentFormSchema = paymentBody.extend({
  amount: z.string().trim().regex(/^\d+$/)
    .transform(Number)
    .pipe(paymentBody.shape.amount),
});
const paymentForm = rhf(createPayment, { schema: paymentFormSchema });
const form = paymentForm.useForm({ defaultValues: { amount: "" } });

const mutation = useMutation(rq(createPayment).mutationOptions());
form.watch("amount"); // string: the field's input
form.handleSubmit((body) => {
  body.amount; // number: suitable for createPayment's request
  body.currency; // string: defaults to "USD"
  mutation.mutate({ body });
});

The selected form schema owns form validation; the adapter does not run the contract schema after it. Derive the form schema from shared request validators, as above, to preserve constraints. Type compatibility checks shapes, not every runtime rule. The client can validate the outgoing request with validateInput, and the server always validates it.

Keep reusable form schemas in features/<feature>/schemas.ts and bindings in features/<feature>/client/forms.ts. A contract must still declare a body. For a scalar or array request body, provide an object-input form schema that transforms named fields into the required request shape.

Reusing transforming schemas

Schema reuse works when parsed values remain valid request inputs and repeat parsing preserves their meaning, such as trimming whitespace or coercing a numeric string to a number. A string-only transform such as z.string().transform(Number) rejects its numeric output on the next parse. A same-type transform such as multiplying a number can change its value again. Use a form-specific schema to perform those conversions before a stable HTTP contract, or explicitly submit the original contract input.

Raw submission

Use submitValues: "raw" to validate with the selected schema while returning the original submitted snapshot:

typescript
const form = rhf(createPayment).useForm({
  submitValues: "raw",
  defaultValues: { amount: 12 },
});

Raw mode does not insert schema defaults or apply transforms to callback values. With a separate form schema, raw values use that form schema's input; they may need mapping before they fit the HTTP contract. Submit callback values rather than rereading form.getValues() after asynchronous validation.

Generated resolvers copy plain objects, arrays, and dates before asynchronous validation, reading their own getters once. Class instances, files, functions, and other opaque values keep their identity so schemas can use their methods and private state. Treat those values as immutable during validation and submission; use a custom resolver if you need application-specific copying.

Form options

Use formOptions(...) when integrating with a wrapper around React Hook Form. It returns options compatible with UseFormProps, including when exactOptionalPropertyTypes is enabled, with matching input and submit output types. The options work with native useForm and createFormControl. Prefer the adapter's useForm(...) for automatic inference. Partial defaultValues can narrow React Hook Form's own inference; when using them with formOptions(...), supply its input, context, and output generics explicitly:

typescript
import type { InferInput, InferOutput } from "@beignet/core/contracts";
import { useForm } from "react-hook-form";

type TodoInput = InferInput<typeof createTodo.config.body>;
type TodoOutput = InferOutput<typeof createTodo.config.body>;
const form = useForm<TodoInput, unknown, TodoOutput>(
  createTodoForm.formOptions({
    defaultValues: { title: "" },
    mode: "onBlur",
  }),
);

A custom resolver controls its own submit output type and takes precedence over resolverEnabled. Do not combine a custom resolver with submitValues; that option only selects output for the generated schema resolver.

Both adapter methods accept forwarded UseFormProps and optional resolver settings. If a conditional custom resolver is undefined, the generated resolver takes over, or input values pass through when resolverEnabled is false. The entire options object may also be undefined, which uses generated validation and parsed submissions. Submit types include the custom output and every possible fallback.

Conditional configurations can choose between a custom resolver and a generated mode, such as useCustom ? { resolver } : { submitValues: "raw" }. The submit type includes the output of each branch. A single configuration still cannot specify both a custom resolver and submitValues. When the entire options object may be absent, returned properties such as defaultValues and mode are optional too.

Disable automatic validation

Set resolverEnabled to false when you want React Hook Form typing without the generated schema resolver. Submit values remain input-shaped: transforms and schema defaults have not run. Combining this with submitValues: "parsed" is rejected by TypeScript and at runtime. A dynamic or optional resolverEnabled flag returns an input/output union because parsing is not guaranteed.

typescript
const form = createTodoForm.useForm({
  resolverEnabled: false,
});

React Hook Form controls when the resolver runs. With the default React Hook Form settings, Beignet's generated resolver validates before submit and then revalidates changed fields after a failed submit. Pass normal React Hook Form options such as mode: "onBlur" or reValidateMode: "onChange" when a form needs different timing.