@beignet/react-hook-form
Runtime: Beignet requires Node.js 22.12 or newer. Bun is optional.
React Hook Form integration for Beignet
[!CAUTION] Beignet is experimental alpha software. The
0.0.xpackage line is for early evaluation, and APIs may change between releases while the framework settles.
This package provides automatic form validation and parsed submissions using a contract body schema, or a separate form schema that produces contract input. The selected form schema must have object-shaped input. It works with any Standard Schema library (Zod, Valibot, ArkType, etc.).
Installation
npm install @beignet/react-hook-form @beignet/core react-hook-form@^7.55.0 @hookform/resolvers@^7.0.1 react
Supports @hookform/resolvers v5, v6, and v7 with React Hook Form 7.55.0 or newer
within v7. Existing v5 and v6 installs remain supported; new starters use v7.
Beignet's Standard Schema integration requires no changes for these upgrades.
Parsed submissions, raw mode, schema defaults and transforms, and optional
resolver settings retain their behavior and inference. 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.
TypeScript requirements
This package requires TypeScript 5.0 or higher for proper type inference.
Agent skills
This package ships a TanStack Intent skill for coding agents:
@beignet/react-hook-form#forms. Load it when adding contract-backed forms,
React Hook Form setup, Standard Schema resolver behavior, rootFormError,
React Query mutations, transforming body schemas, feature component
boundaries, or field/server error mapping in a Beignet app.
Usage
Basic form
These examples use the Todos contracts from the Beignet starter. Create accepts
title; completion belongs to the update contract. For a working form with
verification steps, follow the form guide.
"use client";
import { createReactHookForm } from "@beignet/react-hook-form";
import { createTodo } from "@/features/todos/contracts";
const rhf = createReactHookForm();
function CreateTodoForm() {
const { useForm } = rhf(createTodo);
const form = useForm({
defaultValues: {
title: "",
},
});
const onSubmit = form.handleSubmit((values) => {
// values is parsed schema output: { title: string }
console.log("Creating todo:", values);
});
return (
<form onSubmit={onSubmit}>
<input
{...form.register("title")}
placeholder="What needs to be done?"
/>
{form.formState.errors.title && (
<p className="error">{form.formState.errors.title.message}</p>
)}
<button type="submit" disabled={form.formState.isSubmitting}>
Create Todo
</button>
</form>
);
}
With React Query mutation
"use client";
import { createReactHookForm, rootFormError } from "@beignet/react-hook-form";
import { useMutation } from "@tanstack/react-query";
import { rq } from "@/client";
import { createTodo, listTodos } from "@/features/todos/contracts";
const rhf = createReactHookForm();
function CreateTodoForm() {
const { useForm } = rhf(createTodo);
const form = 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((values) => {
form.clearErrors("root");
mutation.mutate({ body: values });
});
return (
<form onSubmit={onSubmit}>
<input {...form.register("title")} placeholder="Title" readOnly={mutation.isPending} />
{form.formState.errors.title && (
<p>{form.formState.errors.title.message}</p>
)}
{form.formState.errors.root && (
<p>{form.formState.errors.root.message}</p>
)}
<button type="submit" disabled={mutation.isPending}>
{mutation.isPending ? "Creating..." : "Create"}
</button>
</form>
);
}
React Hook Form only owns request body fields. Pass path params, query params,
headers, and auth-derived values to the endpoint call or mutation variables.
Submit failures come back as Beignet client errors, so map route-owned catalog
errors, framework validation errors, network failures, and contract drift
through rootFormError(...), then set form.setError("root", ...) or a
specific field when your server response identifies one.
Disabling validation
If you need to disable the schema resolver (e.g., for partial form handling):
const { useForm } = rhf(createTodo);
const form = useForm({
resolverEnabled: false, // Disable schema validation
defaultValues: { title: "" },
});
Using contract config directly
You can pass either a contract builder or its config:
import { createReactHookForm } from "@beignet/react-hook-form";
import { createTodo } from "@/features/todos/contracts";
const rhf = createReactHookForm();
// Using ContractBuilder directly
const { useForm } = rhf(createTodo);
// Or using the contract config
const { useForm } = rhf(createTodo.config);
API reference
createReactHookForm()
Creates a React Hook Form adapter factory.
const rhf = createReactHookForm();
rhf(contract, options?)
Creates an adapter using the contract body schema by default. Pass { schema }
to bind a separate form schema whose output is assignable to the contract body
input. The selected schema input must be an object with named fields. Scalar
and array bodies require an explicit object-input form schema that produces
the request shape. Contracts without a body are rejected.
const adapter = rhf(createTodo);
adapter.useForm(props?)
Returns a React Hook Form useForm result with the selected schema as resolver.
const form = adapter.useForm({
defaultValues: { title: "" },
resolverEnabled: true, // default
submitValues: "parsed", // default; use "raw" for original input
mode: "onBlur",
});
rootFormError(error, fallback, overrides?)
Maps a failed endpoint call or mutation error to the
form.setError("root", ...) shape. Wraps contractErrorMessage from
@beignet/core/client: non-contract errors return the fallback copy,
client-side input validation failures return a generic "check the highlighted
fields" message, and catalog codes can override copy per form.
form.setError(
"root",
rootFormError(error, "Could not update profile.", {
HANDLE_UNAVAILABLE: "That handle is already taken.",
}),
);
Type inference
- Live fields (
register,watch,setValue,getValues,defaultValues) use the selected schema's input. handleSubmitreceives parsed schema output by default, including transforms, defaults, and removal of unknown keys. Live field state is unchanged.submitValues: "raw"validates but returns the original submitted snapshot.resolverEnabled: falsereturns unparsed input. Explicit parsed mode requires the generated resolver. A dynamic or optional enable flag returns an input/output union.- A custom
resolverowns its output type, even when generation is disabled. It cannot be combined withsubmitValues. - Both adapter methods accept forwarded
UseFormPropsand optional resolvers. An absent override falls back to the generated resolver, or unparsed input when generation is disabled. Submit types include every possible output. Anundefinedoptions object uses generated validation and parsed output. - Conditional configurations may choose a custom resolver or a generated mode;
submit types include each branch's output. A single configuration cannot set
both
resolverandsubmitValues. If the whole options object may be absent, returned properties such asdefaultValuesandmodeare optional too.
Reuse the contract schema
For a number-valued API, use z.number() in the contract and configure the
numeric field with register("amount", { valueAsNumber: true }). Submit parsed
callback values to the typed client; the client sends supplied input unchanged
and the server independently validates it.
Use z.coerce.number() in a shared contract when the API intentionally accepts
numeric strings too. Reusing transforming schemas is appropriate only when
parsed values remain valid request inputs and parsing again preserves their
meaning. z.string().transform(Number) cannot parse its numeric output; even
same-type transforms can change a value again. Use a separate form schema for
such UI conversions, or raw mode to submit original contract input.
Bind a separate form schema
import { defineContract } from "@beignet/core/contracts";
import { createReactHookForm } from "@beignet/react-hook-form";
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 paymentFormSchema = paymentBody.extend({
amount: z.string().trim().regex(/^\d+$/)
.transform(Number)
.pipe(paymentBody.shape.amount),
});
const rhf = createReactHookForm();
const paymentForm = rhf(createPayment, { schema: paymentFormSchema });
const form = paymentForm.useForm({ defaultValues: { amount: "" } });
form.watch("amount"); // string
form.handleSubmit((body) => {
body.amount; // number, matching the request body input
body.currency; // string, including the schema default
});
The form schema owns form validation; the adapter does not additionally run the contract schema. Derive it from shared validators to keep runtime constraints aligned. TypeScript rejects incompatible output shapes but cannot check every runtime rule. Raw or disabled submissions use the form schema's input and may need mapping before posting to the contract.
Use defaultValues for defaults the UI should display. Generated resolvers
copy plain objects, arrays, and dates before asynchronous validation, capturing
own getters once. Class instances, files, functions, and other opaque values
retain their identity; keep them immutable during validation and submission.
Custom resolvers own their validation and snapshot behavior.
Options for React Hook Form wrappers
formOptions(...) returns options compatible with native UseFormProps,
useForm, and createFormControl, including with exactOptionalPropertyTypes
enabled. Input/output types match the adapter's useForm. Partial
defaultValues can narrow React Hook Form's own inference, so supply all three
generics in that case:
import { useForm } from "react-hook-form";
const form = useForm<
z.input<typeof paymentFormSchema>,
unknown,
z.output<typeof paymentFormSchema>
>(paymentForm.formOptions({ defaultValues: { amount: "" } }));
The adapter's useForm infers these automatically. Submit the callback's values
instead of rereading mutable field state through getValues().
Standard Schema support
This package uses the @hookform/resolvers/standard-schema resolver, which works with any Standard Schema compatible library:
- Zod -
z.object({ ... }) - Valibot -
v.object({ ... }) - ArkType -
type({ ... })
Validation behavior
React Hook Form controls when the generated resolver runs. With the default
React Hook Form settings, the 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.
Validation errors are available via form.formState.errors:
{form.formState.errors.title && (
<span className="error">
{form.formState.errors.title.message}
</span>
)}
Complete example
import { createReactHookForm } from "@beignet/react-hook-form";
import { useMutation } from "@tanstack/react-query";
import { rq } from "@/client";
import { rootFormError } from "@/client/errors";
import { updateProfile } from "@/features/profile/contracts";
const rhf = createReactHookForm();
function ProfileForm({ profile }) {
const { useForm } = rhf(updateProfile);
const form = useForm({
defaultValues: {
name: profile.name,
email: profile.email,
bio: profile.bio ?? "",
},
});
const mutation = useMutation(
rq(updateProfile).mutationOptions({
onSuccess: () => {
toast.success("Profile updated!");
},
onError: (error) => {
form.setError("root", rootFormError(error, "Could not update the profile."));
},
})
);
const onSubmit = form.handleSubmit((values) => {
form.clearErrors("root");
mutation.mutate({ body: values });
});
const { errors, isDirty, isSubmitting } = form.formState;
return (
<form onSubmit={onSubmit}>
<div>
<label htmlFor="name">Name</label>
<input id="name" {...form.register("name")} />
{errors.name && <span className="error">{errors.name.message}</span>}
</div>
<div>
<label htmlFor="email">Email</label>
<input id="email" type="email" {...form.register("email")} />
{errors.email && <span className="error">{errors.email.message}</span>}
</div>
<div>
<label htmlFor="bio">Bio</label>
<textarea id="bio" {...form.register("bio")} />
{errors.bio && <span className="error">{errors.bio.message}</span>}
</div>
<button type="submit" disabled={!isDirty || isSubmitting}>
{isSubmitting ? "Saving..." : "Save Changes"}
</button>
{errors.root && <span className="error">{errors.root.message}</span>}
</form>
);
}
Related packages
@beignet/core/contracts- Core contract definitions@beignet/react-query- TanStack Query integration@beignet/core/client- HTTP client
License
MIT