@beignet/react-hook-form

中文文档
0.0.65发布于 2026/11/08MITTypeScriptES Module零依赖近 30 天下载 1927

React Hook Form integration for Beignet with Standard Schema support

原始使用文档
文档目录22 节
  1. Installation
  2. TypeScript requirements
  3. Agent skills
  4. Usage
  5. Basic form
  6. With React Query mutation
  7. Disabling validation
  8. Using contract config directly
  9. API reference
  10. createReactHookForm()
  11. rhf(contract, options?)
  12. adapter.useForm(props?)
  13. rootFormError(error, fallback, overrides?)
  14. Type inference
  15. Reuse the contract schema
  16. Bind a separate form schema
  17. Options for React Hook Form wrappers
  18. Standard Schema support
  19. Validation behavior
  20. Complete example
  21. Related packages
  22. License

@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.x package 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.
  • handleSubmit receives 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: false returns unparsed input. Explicit parsed mode requires the generated resolver. A dynamic or optional enable flag returns an input/output union.
  • A custom resolver owns its output type, even when generation is disabled. It cannot be combined with submitValues.
  • Both adapter methods accept forwarded UseFormProps and optional resolvers. An absent override falls back to the generated resolver, or unparsed input when generation is disabled. Submit types include every possible output. An undefined options 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 resolver and submitValues. If the whole options object may be absent, returned properties such as defaultValues and mode are 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>
  );
}

License

MIT

版本与发布记录

@beignet/react-hook-form 共发布 65 个版本,首次发布于 2026/05/27;过去 12 个月发布了 65 个版本。

版本发布日期距今
0.0.65latest2026/11/08今天
0.0.642026/11/034 天前
0.0.632026/11/026 天前
0.0.622026/11/017 天前
0.0.612026/11/017 天前
0.0.602026/11/017 天前

关于 @beignet/react-hook-form 的常见问题

@beignet/react-hook-form 是什么?

React Hook Form integration for Beignet with Standard Schema support

如何安装 @beignet/react-hook-form?

在项目目录运行 npm install @beignet/react-hook-form,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(^18.0.0 || ^19.0.0)、@beignet/core(>=0.0.3 <1.0.0)、react-hook-form(^7.55.0)、@hookform/resolvers(^5.0.0 || ^6.0.0 || ^7.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@beignet/react-hook-form 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@beignet/react-hook-form 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@beignet/react-hook-form 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22.12.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@beignet/react-hook-form 可以商用吗?

@beignet/react-hook-form 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@beignet/react-hook-form 的下载量有多少?

根据 npm 官方下载统计,@beignet/react-hook-form 在 2026/10/08 – 2026/11/06 这 30 天内被下载 1,927 次,日均约 64 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@beignet/react-hook-form 还在维护吗?

最新版本 0.0.65 发布于 2026/11/08(今天);至今共发布 65 个版本,其中过去 12 个月发布了 65 个;首次发布于 2026/05/27。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。