Search code examples
reactjsreact-hook-form

React-hook-form doesn't set isDirty to false when back to initial state


In the official example for controlled inputs , if you modify the value of an input and then change it back to its initial value, isDirty will be set to true but won't be set back to false and dirtyField will contain the touched field.

In an older example with uncontrolled inputs, we don't have quite same behaviour. In fact, if you modify the value of an input and then change it back to its initial value, isDirty will still be falsy but dirtyFields will not contain the touched field.

Shouldn't isDirty be set back to false when the form is back to its initial state and dirtyFields should be empty?

Is it the intended behaviour?

Does the Controllers break the formState?


Solution

  • isDirty is based on the form input values against default values.

    https://react-hook-form.com/api#formState

    Make sure to provide all inputs' defaultValues at the useForm, so hook form can have a single source of truth to compare whether the form is dirty.

    Here is an example with uncontrolled inputs: https://codesandbox.io/s/bold-kapitsa-7m6o0?file=/src/App.tsx

    example with controlled inputs: https://codesandbox.io/s/dark-framework-op8jy?file=/src/App.tsx