Hook Form React
June 29, 2025 · View on GitHub
This library is a lightweight, dependency-free solution for form validation and submission designed specifically for React applications. The following component libraries have been adapted: Next UI, Ant Design, and MUI.
Recommended to check the examples directly: The examples here are the most up-to-date and the recommended way to use the library.
中文 | English | API | GitHub | Examples: Stackblitz | Examples: GitHub
Developed based on React Hooks and TypeScript, this library aims to provide a concise, efficient, and easily extensible way to handle form validation and submission, whether in simple or complex form scenarios. The design philosophy of this library is compatibility and extensibility, with the idea of supporting developers to achieve the richest functionality with the least amount of code. The core does not bind to any UI component library, thus supporting all React component libraries. Support for third-party component libraries is implemented as independent modules.
Features
- Zero Dependencies: Avoids project bloat and compatibility issues caused by introducing external dependencies.
- Highly Extensible: Can handle various validation rules and form scenarios with simple configurations to meet different needs.
- TypeScript Support: Fully leverages TypeScript's type checking to enhance code readability and maintainability.
- Universality: Adapts to all UI component libraries, providing a unified form-handling solution for React developers.
- Documentation Support: Uses TypeDoc to generate comprehensive documentation, helping developers better understand and use the library's features.
- Flexible Packaging Support: Uses Rollup for packaging, supporting UMD, CommonJS, and ES module formats to adapt to different usage scenarios and environments.
Installation
# pnpm
pnpm add hook-form-react
# yarn
yarn add hook-form-react
# npm
npm i hook-form-react
Usage
Basic Usage
Provides helper tools to make development faster while retaining a high degree of customization.
// Provides helper tools to make development faster while retaining a high degree of customization.
import { Button, Input } from '@nextui-org/react'
import { useAttr, useFormData, Verifications } from 'hook-form-react'
export const Example = () => {
const formData = useFormData(
{ password: '', username: '' },
{
// Supports multiple validations
password: [
// Built-in required validator
// Developers can also add other validation rules in their projects. For details, refer to the developer documentation (to be added).
Verifications.required()
],
username: [
// Built-in required validator + custom message
Verifications.required('User account cannot be empty')
]
}
)
// Use components to quickly bind hooks
const attr = useAttr(formData)
const submit = async () => {
const isValid = await formData.doAllValidate()
console.log('submit:isValid: ', isValid)
if (isValid) {
console.log('formValue', formData.value)
}
}
return (
<div className="p-10 pt-18 pb-0 flex-col">
<Input
placeholder="Please enter your account"
// Quick binding
// NextUI.N_Input belongs to the compatibility layer for [NextUI.Input]
// Developers can also add third-party components in their projects. For details, refer to the developer documentation (to be added).
{...attr('username', attr.NextUI.Input)}
// Custom binding logic
// value={formData.value.username}
// onChange={(e) => formData.pushValue('username', e.target.value)}
// isInvalid={formData.errors.username?.isInvalid}
// errorMessage={formData.errors.username?.msg}
></Input>
<Input
autoComplete="new-password"
type="password"
placeholder="Please enter your password"
{...attr('password', attr.NextUI.Input)}
// Custom binding logic
// value={formData.value.password}
// isInvalid={formData.errors.password?.isInvalid}
// errorMessage={formData.errors.password?.msg}
// onChange={(e) => formData.pushValue('password', e.target.value)}
></Input>
<Button onClick={submit}>Login</Button>
</div>
)
}
Nested Object Forms
Added a hook useSubFormData to handle nested forms. In principle, it can handle object nesting of any number of layers (i.e., infinite nesting).
// useSubFormData
const value10Form = useSubFormData(formData.formData, 'value10', {
haha: [Verifications.required(), Verifications.email()]
})
/**
* Nested object form components need to use this for binding.
*/
const attrValue10 = useAttr(value10Form)
// Submission
const submit = async () => {
const isValid = await formData.doAllValidate()
// Nested forms need separate validation
const isValidValue10 = await value10Form.doAllValidate()
console.log('submit:isValid: ', isValid, isValidValue10)
if (isValid && isValidValue10) {
// The top-level form can access all values
console.log('formValue', formData.value)
}
}
// Reset
const reset = () => {
formData.reset()
// Error states need to be reset separately
value10Form.formErrors.reset()
}
Version Notes
-
Next Version Plans
- Documentation Optimization: Improve documentation accessibility, including usage examples for each API and details for various component libraries.
- Stability Optimization: Optimize the stability and experience of some component libraries.
- Mobile/Mini-Program Component Library Support: The
hook-form-reactmodule is modular and lightweight (around 10k), making it suitable for use in mini-programs. Future plans include adapting toTaromini-program component libraries. - Complete Developer Documentation: Based on the pluggable design principle, adding third-party component library adaptations and custom validations is straightforward. Future efforts will focus on completing developer documentation to help developers customize
hook-form-reactbased on project needs.
V3.0.0
- Refactored API methods for more concise and standardized naming (not backward compatible). Refer to the API documentation for details.
- Automatic validation triggering. Currently supports three validation trigger modes: 'change', 'blur', and 'safeChange'.
/** * Validation triggers */ export enum Trigger { /** Triggers when the variable value changes */ 'change' = 'change', /** Triggers when the input field loses focus */ 'blur' = 'blur', /** Safe variable value change trigger (only triggers when the input field is focused and the variable changes) */ 'safeChange' = 'safeChange' }- Simplified validation rules, removing less commonly used ones.
-
v2.3.0
- MUI Components: Completed adaptation for the
MUIcomponent library. For usage, see Examples.
- MUI Components: Completed adaptation for the
-
v2.2.0
- Antd Components: Form components have been fully adapted (as of this version, we have adapted
Next UIandAntd).import { Antd_5 } from 'hook-form-react/Antd_5'. All adaptations forantdare included here, isolated from the core library. For usage examples, refer to Examples: Stackblitz.
- Antd Components: Form components have been fully adapted (as of this version, we have adapted
-
v2.1.0
- Fixed an issue where immediate assignment and validation could not retrieve the latest form data (a bug caused by React.useState's asynchronous execution). Added two new methods:
doValidateImmeanddoAllValidateImme. If issues are found withdoValidateordoAllValidate, replace them with the corresponding methods. In principle,doValidateanddoAllValidateare recommended first.
- Fixed an issue where immediate assignment and validation could not retrieve the latest form data (a bug caused by React.useState's asynchronous execution). Added two new methods:
-
v2.0.2
- Custom validation rules:
execute?: (value: V, content: any) => Promise<boolean>. Added thecontentparameter to access form context data.
- Custom validation rules:
-
v2.0.0
- Added support for nested object forms. For details, see Stackblitz.
- Added Stackblitz example project (requires VPN).
-
v1.0.0
- Refactored the validation rule implementation for better usability. Added several commonly used validation rules. All common validation rules. Validation rules have not been fully tested; feedback is welcome.
- NextUI Components: All form components have been adapted. All adapted components (any omissions will be added later).
- Fixed inaccurate type declarations.
- Added test projects to verify functionality.
-
v0.5.x (Underlying Implementation Preview)
- The underlying framework is implemented, offering a smooth experience. Refer to Advanced Usage.
- Good overall extensibility. Component library-related code is completely isolated from the core form code, laying the foundation for supporting different component libraries in the future.
- Form data and error states are fully controllable, allowing customization based on business logic.
- Validation rules are uniformly implemented, making extension and customization easy.
- Zero dependencies, purely hooks-based.
Component Library Support Status
-
【90/100】 NextUI: Good experience, with timely fixes for issues (used by the author).
-
【80/100】 MUI: Since MUI itself does not support form validation, using hook-form-react is a good choice. Compared to react-hook-form, it avoids complex concepts.
-
【80/100】 Antd: The built-in form experience is good. Prefer using the built-in forms. Future adaptations will focus on dual-component library scenarios.
-
【60/100】 ......
API Reference
This section should detail the Hooks, functions, their parameters, return types, and usage examples to help developers quickly get started and effectively utilize the library's features.
Contribution Guidelines
We welcome and encourage community contributions, whether through bug reports, feature requests, or direct code submissions. Refer to our contribution guidelines for more information.
License
This project is licensed under the MIT License. For details, see the LICENSE file.