formState: Object
This object contains information about the entire form state. It helps you to keep on track with the user's interaction with your form application.
Return
Name | Type | Description |
---|---|---|
isDirty | boolean | Set to
|
dirtyFields | object | An object with the user-modified fields. Make sure to provide all inputs' defaultValues via useForm, so the library can compare against the
|
touchedFields | object | An object containing all the inputs the user has interacted with. |
defaultValues | object | The value which has been set at useForm's defaultValues or updated defaultValues via reset API. |
isSubmitted | boolean | Set to true after the form is submitted. Will remain true until the reset method is invoked. |
isSubmitSuccessful | boolean | Indicate the form was successfully submitted without any runtime error. |
isSubmitting | boolean | true if the form is currently being submitted. false otherwise. |
isLoading | boolean |
Important: this prop is only applicable to async
|
submitCount | number | Number of times the form was submitted. |
isValid | boolean | Set to true if the form doesn't have any errors.
|
isValidating | boolean | Set to true during validation. |
validatingFields | boolean | Capture fields which are getting async validation. |
errors | object | An object with field errors. There is also an ErrorMessage component to retrieve error message easily. |
Rules
formState
is wrapped with a Proxy to improve render performance and skip extra logic if specific state is not subscribed to. Therefore make sure you invoke or read it before arender
in order to enable the state update.formState
is updated in batch. If you want to subscribe toformState
viauseEffect
, make sure that you place the entireformState
in the optional array.useEffect(() => {if (formState.errors.firstName) {// do the your logic here}}, [formState]); // ✅// ❌ formState.errors will not trigger the useEffectPay attention to the logical operator when subscription to
formState
.// ❌ formState.isValid is accessed conditionally,// so the Proxy does not subscribe to changes of that statereturn <button disabled={!formState.isDirty || !formState.isValid} />;// ✅ read all formState values to subscribe to changesconst { isDirty, isValid } = formState;return <button disabled={!isDirty || !isValid} />;
Examples
import React from "react";import { useForm } from "react-hook-form";export default function App() {const {register,handleSubmit,// Read the formState before render to subscribe the form state through the ProxyformState: { errors, isDirty, isSubmitting, touchedFields, submitCount },} = useForm();const onSubmit = (data) => console.log(data);return (<form onSubmit={handleSubmit(onSubmit)}><input {...register("test")} /><input type="submit" /></form>);}
Video
The following video will explain in detail different form states.