reset: (values?: Record<string, any>, options?: Record<string, boolean>) => void
Reset either the entire form state or part of the form state.
Props
Reset
has the ability to retain formState. Here are the options you may use:
Name | Type | Description |
---|---|---|
values | object | An optional object to reset form values. |
keepErrors | boolean | All errors will remain. This will not guarantee with further user actions. |
keepDirty | boolean |
Important: this keep option doesn't reflect form input values but only dirty fields form state. |
keepValues | boolean | Form input values will be unchanged. |
keepDefaultValues | boolean | Keep the same defaultValues which are initialised via
|
keepIsSubmitted | boolean |
|
keepTouched | boolean |
|
keepIsValid | boolean |
|
keepSubmitCount | boolean |
|
Rules
For controlled components you will need to pass
defaultValues
touseForm
in order toreset
theController
components' value.When
defaultValues
is not supplied toreset
API, then HTML native reset API will be invoked to restore the form.Avoid calling
reset
beforeuseForm
'suseEffect
is invoked, this is becauseuseForm
's subscription needs to be ready beforereset
can send a signal to flush form state update.You can
reset
insideuseEffect
.useEffect(() => { reset({ data: 'test' }) }, [isSubmitSuccessful])
Examples
import React, { useCallback } from "react";
import { useForm } from "react-hook-form";
export default function App() {
const { register, handleSubmit, reset } = useForm();
const onSubmit = (data, e) => {};
const resetAsyncForm = useCallback(async () => {
const result = await fetch('./api/formValues.json'); // result: { firstName: 'test', lastName: 'test2' }
reset(result); // asynchronously reset your form values
}, [reset]);
useEffect(() => {
resetAsyncForm()
}, [resetForm])
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register("firstName", { required: true })} />
<input {...register("lastName")} />
<input type="reset" /> // standard reset button
<input type="button" onClick={() => reset({ firstName: "bill" }); }} /> // reset form with values
<input type="button" onClick={() => {
reset({
firstName: "bill"
}, {
keepErrors: true,
keepDirty: true,
keepIsSubmitted: false,
keepTouched: false,
keepIsValid: false,
keepSubmitCount: false,
});
}} />
</form>
);
}
Video
The following video explains in detail each different formState
represents and functionality within the reset
API.
Thank you for your support
If you find React Hook Form to be useful in your project, please consider to star and support it.