React hook Form know when value is modified

Viewed 12883

How can we know form is modified or not in react-hook-form. Anyone have idea. I want know if any of the value is changed and update the state edited to true.

After i provide the defaultValue to useForm({defaultValues:values}). I want to notified when the values is updated or changed from defaultValue.

3 Answers

Use isDirty property

function YourComponent() {
 const { formState } = useForm();
 const isFormEdited = formState.isDirty;
 ....

Here is the docs reference

Figured out how to accomplished this. It is important to specify the defaultValues property.

See the isDirty section of formState documentation:

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.

And a short example:

  const {
    formState: {
      isDirty, 
    },
  } = useForm<ProfileFormInterface>({
    defaultValues: {name: 'John Doe', email: 'jd@johndoe.com'},
  })

isDirty will now only be true if the name or email changes.

You can use dirtyFields from formstate also, check the length of the fields modified.

const [isEdited, setIsEdited] = useState(false);
const fieldsEdited = formState.dirtyFields;
useEffect(() => {
    if (Object.keys(fieldsEdited).length > 0) {
        setIsEdited(true);
    } else {
        setIsEdited(false);
    }
}, [fieldsEdited]);
Related