Token导航 LogoToken导航TokenDH.com
开发需要联网github未标认证来源可访问许可证需确认审计通过

react-hook-form-zodReact hook form ZOD 问题管理

Agent Skill

用于辅助前端页面、组件、样式和交互逻辑的开发与维护。它适合让 Agent 生成或审查 React、Next.js、Vue、Tailwind、CSS 等相关代码,整理组件结构,或定位布局和性能问题。使用时需要结合项目现有设计系统、路由和构建方式,避免只生成孤立片段;涉及页面改动时,应配合本地预览和构建检查确认视觉效果。

总安装

612

周安装

26

GitHub Stars

3

下载量

214
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:react-hook-form-zod(React hook form ZOD 问题管理)
来源仓库:https://github.com/fellipeutaka/leon
仓库路径:skills/react-hook-form-zod
安装命令:
npx skills add https://github.com/fellipeutaka/leon --skill react-hook-form-zod
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/fellipeutaka/leon --skill react-hook-form-zod

简介

react-hook-form-zod 用于辅助前端页面和组件的开发与维护。

  • 适合生成或审查 React、Next.js、Vue 等相关代码。
  • 使用时需结合现有设计系统和路由方式,避免孤立片段。
  • 涉及页面改动时应配合本地预览确认视觉效果。react-hook-form-zod 属于开发类 Skill,可作为该场景下的辅助能力补充。
  • 应关注组件结构和性能优化,而非仅装饰性调整。

SKILL.md

React Hook Form + Zod Validation

Status: Production Ready ✅ Last Verified: 2026-01-20 Latest Versions: react-hook-form@7.71.1, zod@4.3.5, @hookform/resolvers@5.2.2


Quick Start

npm install react-hook-form@7.70.0 zod@4.3.5 @hookform/resolvers@5.2.2

Basic Form Pattern:

const schema = z.object({
  email: z.string().email(),
  password: z.string().min(8),
})

// zodResolver infers types — no need for z.infer<typeof schema> on useForm
const form = useForm({
  resolver: zodResolver(schema),
  defaultValues: { email: '', password: '' }, // REQUIRED to prevent uncontrolled warnings
})

const onSubmit = form.handleSubmit((value) => {
  console.log(value)
})

<form onSubmit={onSubmit}>
  <input {...form.register('email')} />
  {form.formState.errors.email && <span role="alert">{form.formState.errors.email.message}</span>}
</form>

Server Validation (CRITICAL - never skip):

// SAME schema on server
const data = schema.parse(await req.json())

Key Patterns

useForm Options (validation modes):

  • mode: 'onSubmit' (default) - Best performance
  • mode: 'onBlur' - Good balance
  • mode: 'onChange' - Live feedback, more re-renders
  • shouldUnregister: true - Remove field data when unmounted (use for multi-step forms)

Zod Refinements (cross-field validation):

z.object({ password: z.string(), confirm: z.string() })
  .refine((data) => data.password === data.confirm, {
    message: "Passwords don't match",
    path: ['confirm'], // CRITICAL: Error appears on this field
  })

Zod Transforms:

z.string().transform((val) => val.toLowerCase()) // Data manipulation
z.string().transform(parseInt).refine((v) => v > 0) // Chain with refine

Zod v4.3.0+ Features:

// Exact optional (can omit field, but NOT undefined)
z.string().exactOptional()

// Exclusive union (exactly one must match)
z.xor([z.string(), z.number()])

// Import from JSON Schema
z.fromJSONSchema({ type: "object", properties: { name: { type: "string" } } })

zodResolver connects Zod to React Hook Form, preserving type safety


Registration

register (for standard HTML inputs):

<input {...form.register('email')} /> // Uncontrolled, best performance

Controller (for third-party components):

<Controller
  name="category"
  control={form.control}
  render={({ field }) => <CustomSelect {...field} />} // MUST spread {...field}
/>

When to use Controller: React Select, date pickers, custom components without ref. Otherwise use register.


Error Handling

Display errors:

{form.formState.errors.email && <span role="alert">{form.formState.errors.email.message}</span>}
{form.formState.errors.address?.street?.message} // Nested errors (use optional chaining)

Server errors:

const onSubmit = form.handleSubmit(async (data) => {
  const res = await fetch('/api/submit', { method: 'POST', body: JSON.stringify(data) })
  if (!res.ok) {
    const { errors: serverErrors } = await res.json()
    Object.entries(serverErrors).forEach(([field, msg]) => form.setError(field, { message: msg }))
  }
})

Advanced Patterns

useFieldArray (dynamic lists):

const { fields, append, remove } = useFieldArray({ control: form.control, name: 'contacts' })

{fields.map((field, index) => (
  <div key={field.id}> {/* CRITICAL: Use field.id, NOT index */}
    <input {...form.register(`contacts.${index}.name` as const)} />
    {form.formState.errors.contacts?.[index]?.name && <span>{form.formState.errors.contacts[index].name.message}</span>}
    <button onClick={() => remove(index)}>Remove</button>
  </div>
))}
<button onClick={() => append({ name: '', email: '' })}>Add</button>

Async Validation (debounce):

const debouncedValidation = useDebouncedCallback(() => form.trigger('username'), 500)

Multi-Step Forms:

const step1 = z.object({ name: z.string(), email: z.string().email() })
const step2 = z.object({ address: z.string() })
const fullSchema = step1.merge(step2)

const nextStep = async () => {
  const isValid = await form.trigger(['name', 'email']) // Validate specific fields
  if (isValid) setStep(2)
}

Conditional Validation:

z.discriminatedUnion('accountType', [
  z.object({ accountType: z.literal('personal'), name: z.string() }),
  z.object({ accountType: z.literal('business'), companyName: z.string() }),
])

Conditional Fields with shouldUnregister:

const form = useForm({
  resolver: zodResolver(schema),
  shouldUnregister: false, // Keep values when fields unmount (default)
})

// Or use conditional schema validation:
z.object({
  showAddress: z.boolean(),
  address: z.string(),
}).refine((data) => {
  if (data.showAddress) {
    return data.address.length > 0;
  }
  return true;
}, {
  message: "Address is required",
  path: ["address"],
})

shadcn/ui Integration

Note: shadcn/ui deprecated the Form component. Use the Field component for new implementations (check latest docs).

Common Import Mistake: IDEs/AI may auto-import Form from "react-hook-form" instead of from shadcn. Always import:

// ✅ Correct:
import { useForm } from "react-hook-form";
import { Form, FormField, FormItem } from "@/components/ui/form"; // shadcn

// ❌ Wrong (auto-import mistake):
import { useForm, Form } from "react-hook-form";

Legacy Form component:

<FormField control={form.control} name="username" render={({ field }) => (
  <FormItem>
    <FormControl><Input {...field} /></FormControl>
    <FormMessage />
  </FormItem>
)} />

Performance

  • Use register (uncontrolled) over Controller (controlled) for standard inputs
  • Use watch('email') not watch() (isolates re-renders to specific fields)
  • shouldUnregister: true for multi-step forms (clears data on unmount)

Large Forms (300+ Fields)

Warning: Forms with 300+ fields using a resolver (Zod/Yup) AND reading formState properties can freeze for 10-15 seconds during registration. (Issue #13129)

Performance Characteristics:

  • Clean (no resolver, no formState read): Almost immediate
  • With resolver only: Almost immediate
  • With formState read only: Almost immediate
  • With BOTH resolver + formState read: ~9.5 seconds for 300 fields

Workarounds:

  1. Avoid destructuring formState - Read properties inline only when needed:
// ❌ Slow with 300+ fields:
const { isDirty, isValid } = form.formState;

// ✅ Fast:
const handleSubmit = () => {
  if (!form.formState.isValid) return; // Read inline only when needed
};
  1. Use mode: "onSubmit" - Don't validate on every change:
const form = useForm({
  resolver: zodResolver(largeSchema),
  mode: "onSubmit", // Validate only on submit, not onChange
});
  1. Split into sub-forms - Multiple smaller forms with separate schemas:
// Instead of one 300-field form, use 5-6 forms with 50-60 fields each
const form1 = useForm({ resolver: zodResolver(schema1) }); // Fields 1-50
const form2 = useForm({ resolver: zodResolver(schema2) }); // Fields 51-100
  1. Lazy render fields - Use tabs/accordion to mount only visible fields:
// Only mount fields for active tab, reduces initial registration time
{activeTab === 'personal' && <PersonalInfoFields />}
{activeTab === 'address' && <AddressFields />}

Critical Rules

Always set defaultValues (prevents uncontrolled→controlled warnings)

Validate on BOTH client and server (client can be bypassed - security!)

Use field.id as key in useFieldArray (not index)

Use const form = useForm(...) — access via form.control, form.handleSubmit, form.formState, form.reset(), etc. Do not destructure.

const onSubmit = form.handleSubmit((value) => {...}) — extract the submit handler, don't inline it in onSubmit={}

z.infer<typeof schema> is optional — zodResolver infers types automatically. Only use it when you need the type explicitly elsewhere (e.g. function signatures, props).

Never skip server validation (security vulnerability)

Never mutate values directly (use form.setValue())

Never mix controlled + uncontrolled patterns

Never use index as key in useFieldArray


Known Issues (20 Prevented)

  1. Zod v4 Type Inference - #13109: Use z.infer<typeof schema> explicitly. Resolved in v7.66.x+. Note: @hookform/resolvers has TypeScript compatibility issues with Zod v4 (#813). Workaround: Use import {z} from 'zod/v3' or wait for resolver update.
  2. Uncontrolled→Controlled Warning - Always set defaultValues for all fields
  3. Nested Object Errors - Use optional chaining: errors.address?.street?.message
  4. Array Field Re-renders - Use key={field.id} in useFieldArray (not index)
  5. Async Validation Race Conditions - Debounce validation, cancel pending requests
  6. Server Error Mapping - Use setError() to map server errors to fields
  7. Default Values Not Applied - Set defaultValues in useForm options (not useState)
  8. Controller Field Not Updating - Always spread {...field} in render function
  9. useFieldArray Key Warnings - Use field.id as key (not index)
  10. Schema Refinement Error Paths - Specify path in refinement: refine(..., {path: ['fieldName']})
  11. Transform vs Preprocess - Use transform for output, preprocess for input
  12. Multiple Resolver Conflicts - Use single resolver (zodResolver), combine schemas if needed
  13. Zod v4 Optional Fields Bug - #13102: Setting optional fields (.optional()) to empty string "" incorrectly triggers validation errors. Workarounds: Use .nullish(), .or(z.literal("")), or z.preprocess((val) => val === ""? undefined: val, z.email().optional())
  14. useFieldArray Primitive Arrays Not Supported - #12570: Design limitation. useFieldArray only works with arrays of objects, not primitives like string[]. Workaround: Wrap primitives in objects: [{value: "string"}] instead of ["string"]
  15. useFieldArray SSR ID Mismatch - #12782: Hydration mismatch warnings with SSR (Remix, Next.js). Field IDs generated on server don't match client. Workaround: Use client-only rendering for field arrays or wait for V8 (uses deterministic key)
  16. Next.js 16 reset() Validation Bug - #13110: Calling form.reset() after Server Actions submission causes validation errors on next submit. Fixed in v7.65.0+. Before fix: Use setValue() instead of reset()
  17. Validation Race Condition - #13156: During resolver validation, intermediate render where isValidating=false but errors not populated yet. Don't derive validity from errors alone. Use: !errors.field &&!isValidating
  18. ZodError Thrown in Beta Versions - #12816: Zod v4 beta versions throw ZodError directly instead of capturing in formState.errors. Fixed in stable Zod v4.1.x+. Avoid beta versions
  19. Large Form Performance - #13129: 300+ fields with resolver + formState read freezes for 10-15 seconds. See Performance section for 4 workarounds
  20. shadcn Form Import Confusion - IDEs/AI may auto-import Form from "react-hook-form" instead of shadcn. Always import Form components from @/components/ui/form

Upcoming Changes in V8 (Beta)

React Hook Form v8 (currently in beta as of v8.0.0-beta.1, released 2026-01-11) introduces breaking changes. RFC Discussion #7433

Breaking Changes:

  1. useFieldArray: idkey:
// V7:
const { fields } = useFieldArray({ control, name: "items" });
fields.map(field => <div key={field.id}>...</div>)

// V8:
const { fields } = useFieldArray({ control, name: "items" });
fields.map(field => <div key={field.key}>...</div>)
// keyName prop removed
  1. Watch component: namesname:
// V7:
<Watch names={["email", "password"]} />

// V8:
<Watch name={["email", "password"]} />
  1. watch() callback API removed:
// V7:
watch((data, { name, type }) => {
  console.log(data, name, type);
});

// V8: Use useWatch or manual subscription
const data = useWatch({ control });
useEffect(() => {
  console.log(data);
}, [data]);
  1. setValue() no longer updates useFieldArray:
// V7:
setValue("items", newArray); // Updates field array

// V8: Must use replace() API
const { replace } = useFieldArray({ control, name: "items" });
replace(newArray);

V8 Benefits:

  • Fixes SSR hydration mismatch (deterministic key instead of random id)
  • Improved performance
  • Better TypeScript inference

Migration Timeline: V8 is in beta. Stable release date TBD. Monitor releases for stable version.


Bundled Resources

Templates: basic-form.tsx, advanced-form.tsx, shadcn-form.tsx, server-validation.ts, async-validation.tsx, dynamic-fields.tsx, multi-step-form.tsx, package.json

References: zod-schemas-guide.md, rhf-api-reference.md, error-handling.md, performance-optimization.md, shadcn-integration.md, top-errors.md

Docs: https://react-hook-form.com/ | https://zod.dev/ | https://ui.shadcn.com/docs/components/form


License: MIT | Last Verified: 2026-01-20 | Skill Version: 2.1.0 | Changes: Added 8 new known issues (Zod v4 optional fields bug, useFieldArray primitives limitation, SSR hydration mismatch, performance guidance for large forms, Next.js 16 reset() bug, validation race condition, ZodError thrown in beta, shadcn import confusion), added Zod v4.3.0 features (.exactOptional(),.xor(), z.fromJSONSchema()), added conditional field patterns with shouldUnregister, added V8 beta breaking changes section, expanded Zod v4 resolver compatibility notes, updated to react-hook-form@7.71.1

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

35.03%
按下载量换算75

Claude

30.91%
按下载量换算66

Cursor

16.2%
按下载量换算35

Gemini CLI

9.58%
按下载量换算21

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills