react-hook-form

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

React Hook Form Best Practices

React Hook Form 最佳实践

Comprehensive performance optimization guide for React Hook Form applications. Contains 41 rules across 8 categories, prioritized by impact to guide form development, automated refactoring, and code generation.
这是一份针对React Hook Form应用的全面性能优化指南。包含8个类别共41条规则,按影响优先级排序,可用于指导表单开发、自动化重构和代码生成。

When to Apply

适用场景

Reference these guidelines when:
  • Writing new forms with React Hook Form
  • Configuring useForm options (mode, defaultValues, validation)
  • Subscribing to form values with watch/useWatch
  • Integrating controlled UI components (MUI, shadcn, Ant Design)
  • Managing dynamic field arrays with useFieldArray
  • Reviewing forms for performance issues
在以下场景中可参考这些指南:
  • 使用React Hook Form编写新表单
  • 配置useForm选项(mode、defaultValues、validation)
  • 使用watch/useWatch订阅表单值
  • 集成受控UI组件(MUI、shadcn、Ant Design)
  • 使用useFieldArray管理动态字段数组
  • 检查表单的性能问题

Rule Categories by Priority

按优先级划分的规则类别

PriorityCategoryImpactPrefix
1Form ConfigurationCRITICAL
formcfg-
2Field SubscriptionCRITICAL
sub-
3Controlled ComponentsHIGH
ctrl-
4Validation PatternsHIGH
valid-
5Field ArraysMEDIUM-HIGH
array-
6State ManagementMEDIUM
formstate-
7Integration PatternsMEDIUM
integ-
8Advanced PatternsLOW
adv-
优先级类别影响程度前缀
1表单配置关键
formcfg-
2字段订阅关键
sub-
3受控组件
ctrl-
4验证模式
valid-
5字段数组中高
array-
6状态管理
formstate-
7集成模式
integ-
8高级模式
adv-

Quick Reference

快速参考

1. Form Configuration (CRITICAL)

1. 表单配置(关键)

  • formcfg-validation-mode
    - Use onSubmit mode for optimal performance
  • formcfg-revalidate-mode
    - Set reValidateMode to onBlur for post-submit performance
  • formcfg-default-values
    - Always provide defaultValues for form initialization
  • formcfg-async-default-values
    - Use async defaultValues for server data
  • formcfg-should-unregister
    - Enable shouldUnregister for dynamic form memory efficiency
  • formcfg-useeffect-dependency
    - Avoid useForm return object in useEffect dependencies
  • formcfg-validation-mode
    - 使用onSubmit模式以获得最佳性能
  • formcfg-revalidate-mode
    - 将reValidateMode设置为onBlur以提升提交后性能
  • formcfg-default-values
    - 始终为表单初始化提供defaultValues
  • formcfg-async-default-values
    - 为服务端数据使用异步defaultValues
  • formcfg-should-unregister
    - 启用shouldUnregister以提升动态表单的内存效率
  • formcfg-useeffect-dependency
    - 避免在useEffect依赖项中使用useForm返回对象

2. Field Subscription (CRITICAL)

2. 字段订阅(关键)

  • sub-usewatch-over-watch
    - Use useWatch instead of watch for isolated re-renders
  • sub-watch-specific-fields
    - Watch specific fields instead of entire form
  • sub-usewatch-with-getvalues
    - Combine useWatch with getValues for timing safety
  • sub-deep-subscription
    - Subscribe deep in component tree where data is needed
  • sub-avoid-watch-in-render
    - Avoid calling watch() in render for one-time reads
  • sub-usewatch-default-value
    - Provide defaultValue to useWatch for initial render
  • sub-useformcontext-sparingly
    - Use useFormContext sparingly for deep nesting
  • sub-usewatch-over-watch
    - 使用useWatch而非watch以实现独立重渲染
  • sub-watch-specific-fields
    - 仅监听特定字段而非整个表单
  • sub-usewatch-with-getvalues
    - 结合useWatch与getValues以确保时序安全
  • sub-deep-subscription
    - 在组件树中需要数据的深层位置进行订阅
  • sub-avoid-watch-in-render
    - 避免在渲染中调用watch()进行一次性读取
  • sub-usewatch-default-value
    - 为useWatch提供defaultValues以完成初始渲染
  • sub-useformcontext-sparingly
    - 谨慎使用useFormContext以处理深层嵌套

3. Controlled Components (HIGH)

3. 受控组件(高)

  • ctrl-usecontroller-isolation
    - Use useController for re-render isolation
  • ctrl-avoid-double-registration
    - Avoid double registration with useController
  • ctrl-controller-field-props
    - Wire Controller field props correctly for UI libraries
  • ctrl-single-usecontroller-per-component
    - Use single useController per component
  • ctrl-local-state-combination
    - Combine local state with useController for UI-only state
  • ctrl-usecontroller-isolation
    - 使用useController实现重渲染隔离
  • ctrl-avoid-double-registration
    - 避免使用useController时出现双重注册
  • ctrl-controller-field-props
    - 为UI库正确关联Controller字段属性
  • ctrl-single-usecontroller-per-component
    - 每个组件仅使用一个useController实例
  • ctrl-local-state-combination
    - 结合本地状态与useController以处理仅UI相关的状态

4. Validation Patterns (HIGH)

4. 验证模式(高)

  • valid-resolver-caching
    - Define schema outside component for resolver caching
  • valid-dynamic-schema-factory
    - Use schema factory for dynamic validation
  • valid-error-message-strategy
    - Access errors via optional chaining or lodash get
  • valid-inline-vs-resolver
    - Prefer resolver over inline validation for complex rules
  • valid-delay-error
    - Use delayError to debounce rapid error display
  • valid-native-validation
    - Consider native validation for simple forms
  • valid-resolver-caching
    - 在组件外部定义schema以实现解析器缓存
  • valid-dynamic-schema-factory
    - 使用schema工厂实现动态验证
  • valid-error-message-strategy
    - 通过可选链或lodash get访问错误信息
  • valid-inline-vs-resolver
    - 对于复杂规则,优先使用resolver而非内联验证
  • valid-delay-error
    - 使用delayError实现错误提示的防抖
  • valid-native-validation
    - 对于简单表单,可考虑使用原生验证

5. Field Arrays (MEDIUM-HIGH)

5. 字段数组(中高)

  • array-use-field-id-as-key
    - Use field.id as key in useFieldArray maps
  • array-complete-default-objects
    - Provide complete default objects for field array operations
  • array-separate-crud-operations
    - Separate sequential field array operations
  • array-unique-fieldarray-per-name
    - Use single useFieldArray instance per field name
  • array-virtualization-formprovider
    - Use FormProvider for virtualized field arrays
  • array-use-field-id-as-key
    - 在useFieldArray映射中使用field.id作为key
  • array-complete-default-objects
    - 为字段数组操作提供完整的默认对象
  • array-separate-crud-operations
    - 拆分连续的字段数组操作
  • array-unique-fieldarray-per-name
    - 每个字段名称仅使用一个useFieldArray实例
  • array-virtualization-formprovider
    - 为虚拟化字段数组使用FormProvider

6. State Management (MEDIUM)

6. 状态管理(中)

  • formstate-destructure-formstate
    - Destructure formState properties before render
  • formstate-useformstate-isolation
    - Use useFormState for isolated state subscriptions
  • formstate-getfieldstate-for-single-field
    - Use getFieldState for single field state access
  • formstate-subscribe-to-specific-fields
    - Subscribe to specific field names in useFormState
  • formstate-avoid-isvalid-with-onsubmit
    - Avoid isValid with onSubmit mode for button state
  • formstate-destructure-formstate
    - 在渲染前解构formState属性
  • formstate-useformstate-isolation
    - 使用useFormState实现独立状态订阅
  • formstate-getfieldstate-for-single-field
    - 使用getFieldState访问单个字段的状态
  • formstate-subscribe-to-specific-fields
    - 在useFormState中订阅特定字段名称
  • formstate-avoid-isvalid-with-onsubmit
    - 在onSubmit模式下避免使用isValid控制按钮状态

7. Integration Patterns (MEDIUM)

7. 集成模式(中)

  • integ-shadcn-form-import
    - Verify shadcn Form component import source
  • integ-shadcn-select-wiring
    - Wire shadcn Select with onValueChange instead of spread
  • integ-mui-controller-pattern
    - Use Controller for Material-UI components
  • integ-value-transform
    - Transform values at Controller level for type coercion
  • integ-shadcn-form-import
    - 验证shadcn Form组件的导入源
  • integ-shadcn-select-wiring
    - 使用onValueChange而非展开操作关联shadcn Select
  • integ-mui-controller-pattern
    - 为Material-UI组件使用Controller
  • integ-value-transform
    - 在Controller层转换值以实现类型转换

8. Advanced Patterns (LOW)

8. 高级模式(低)

  • adv-formprovider-memo
    - Wrap FormProvider children with React.memo
  • adv-devtools-performance
    - Disable DevTools in production and during performance testing
  • adv-testing-wrapper
    - Create test wrapper with QueryClient and AuthProvider
  • adv-formprovider-memo
    - 使用React.memo包裹FormProvider的子组件
  • adv-devtools-performance
    - 在生产环境和性能测试期间禁用DevTools
  • adv-testing-wrapper
    - 创建包含QueryClient和AuthProvider的测试包装器

How to Use

使用方法

Read individual reference files for detailed explanations and code examples:
  • Section definitions - Category structure and impact levels
  • Rule template - Template for adding new rules
  • Reference files:
    references/{prefix}-{slug}.md
阅读单个参考文件以获取详细说明和代码示例:
  • 章节定义 - 类别结构和影响级别
  • 规则模板 - 添加新规则的模板
  • 参考文件:
    references/{prefix}-{slug}.md

Related Skills

相关技能

  • For schema validation with Zod resolver, see
    zod
    skill
  • For React 19 server actions, see
    react-19
    skill
  • For UI/UX form design, see
    frontend-design
    skill
  • 如需使用Zod解析器进行schema验证,请查看
    zod
    技能
  • 如需React 19服务端操作,请查看
    react-19
    技能
  • 如需UI/UX表单设计,请查看
    frontend-design
    技能

Full Compiled Document

完整编译文档

For the complete guide with all rules expanded:
AGENTS.md
如需查看包含所有扩展规则的完整指南:
AGENTS.md