Skip to content

useForm

React hooks for form validation

useForm: UseFormProps

useForm is custom hook for managing forms with ease. It takes optional arguments. The following example demonstrates all of the arguments along with their default values.

Props

mode: onChange | onBlur | onSubmit | onTouched | all = 'onSubmit'React Native: compatible with Controller

This option allows you to configure the validation strategy before user submit the form (onSubmit event).

NameTypeDescription
onSubmitstringValidation will trigger on the submit event and invalid inputs will attach onChange event listeners to re-validate them.
onBlurstringValidation will trigger on the blur event.
onChangestringValidation will trigger on the change event with each input, and lead to multiple re-renders. Warning: this often comes with a significant impact on performance.
onTouchedstring

Validation will trigger on the first blur event. After that, it will trigger on every change event.

Note: when using with Controller, make sure to wire up onBlur with the render prop.

allstringValidation will trigger on the blur and change events.
reValidateMode: onChange | onBlur | onSubmit = 'onChange'React Native: Custom register or using Controller

This option allows you to configure validation strategy when inputs with errors get re-validated after user submits the form (onSubmit event). By default, validation is triggered during the input change event.

defaultValues: Record<string, any> = {}

The defaultValues for inputs are used as the initial value when a component is first rendered, before a user interacts with it. It is encouraged that you set defaultValues for all inputs to non-undefined values such as the empty string or null.

You can set an input's default value with defaultValue/defaultChecked (read more from the React doc for Default Values). You can pass defaultValues as an optional argument to useForm() to populate the default values for the entire form, or set values on an individual Controller component via its defaultValue property. If both defaultValue and defaultValues are set, the value from defaultValues will be used.

Rules

  • Important: You should provide a proper default value and avoid undefined.

    • undefined is reserved for fallback from inline defaultValue/defaultChecked to hook level defaultValues.

    • undefined value is conflicting with controlled component as default state

  • defaultValues are cached on the first render within the custom hook. If you want to reset the defaultValues, you should use the reset api.

  • defaultValues will be injected into watch, useWatch, Controller and useController's defaultValue.

  • defaultValues will be included in the submission result by default, if this is not the desired behavior use shouldUnregister: true instead which means input values will host within all the fields.

  • Avoid including custom object into the defaultValues. eg: moment, luxonas those will lead to unexpected result during internal object clone process.

  • There are other options to include form data:

context:
object

This context object is mutable and will be injected into the resolver's second argument or Yup validation's context object.


CodeSandbox

criteriaMode
firstError | all

  • When set to firstError (default), only the first error from each field will be gathered.

  • When set to all, all errors from each field will be gathered.

CodeSandbox

shouldFocusError
boolean = true

When set to true (default) and the user submits a form that fails the validation, it will set focus on the first field with an error.

Note: only registered fields with a ref will work. Custom registered inputs do not apply. For example: register('test') // doesn't work

Note: the focus order is based on the register order.

delayError
number

This config will delay the error state to be displayed to the end-user in milliseconds. Correct the error input will remove the error instantly and delay will not be applied.

CodeSandbox
shouldUnregister: boolean = false

By default, an input value will be retained when input is removed. However, you can set shouldUnregister to true to unregister input during unmount.

  • This is a global config that overwrites child-level config, if you want to have individual behavior, then you should set the config at the component or hook level, not at useForm.

  • By default shouldUnregister: false: unmounted fields will not be validated by build-in validation.

  • By setting shouldUnregister to true at useForm level, defaultValues will not be merged against submission result.

  • set shouldUnregister: true will set your form behave more closer as native.

    Form values will be lived inside your inputs itself.

    • input unmount will remove value.

    • input hidden should be applied for hidden data.

    • only registered input will be included as submission data.

    • unmounted input will need to notify at either useForm, or useWatch's useEffect for hook form to verify input is unmounted from the DOM.

shouldUseNativeValidation: boolean = false

This config will enable browser native validation. It will also enable CSS selectors :valid and:invalid making style inputs easier. In fact, you can still use those selectors even the client validation is disabled.

  • You can turn on this config and set novalidate at your form and still use those CSS selectors.

  • This feature only works for register API, not useController/Controller.

Examples

resolver: Resolver

This function allows you to use any external validation library such as Yup, Zod, Joi, Superstruct, Vest and many others. The goal is to make sure you can seamlessly integrate whichever validation library you prefer. If you're not using a library, you can always write your own logic to validate your forms.

npm install @hookform/resolvers

Props

NameTypeDescription

values

object

This object contains the entire form values.

context

object

This is the context object which you can provide to the useForm config. It is a mutable object that can be changed on each re-render.

options

{ criteriaMode: string, fields: object, names: string[] }

This is the option object contains information about the validated fields, names and criteriaMode from useForm.

Rules

  • Schema validation focus on the field level for error reporting. Parent level error look is only limited to the direct parent level that is applicable for components such as group checkboxes.

  • This function will be cached.

  • Re-validation of an input will only occur one field at time during a user’s interaction. The lib itself will evaluate the error object to trigger a re-render accordingly.

  • A resolver cannot be used with the built-in validators (e.g.: required, min, etc.)

  • When building a custom resolver:

    • Make sure you are returning an object that has both a values and an errors property. Their default values should be an empty object. For example: {}.

    • The keys of the error object should match the name values of your fields.

Examples

Thank you for your support

If you find React Hook Form to be useful in your project, please consider to star and support it.

Edit