Skip to main content

Reset Form

There're two common ways to reset all form data: reset after form submission and reset form manually. You might ask "how about the reset button?" Well... according to the UX research, which summarized: "Most Web forms would have improved usability if the Reset button was removed." So, generally not recommend but still supported.

Reset After Form Submission#

We can use React Cool Form's reset method (also available from the onSubmit handler) to restore the form to its default values as well as clear/reset all the related state.

Edit RCF - Reset Form

import { useForm } from "react-cool-form";
const Field = ({ label, id, ...rest }) => (
<div>
<label htmlFor={id}>{label}</label>
<input id={id} {...rest} />
</div>
);
const App = () => {
const { form } = useForm({
defaultValues: { firstName: "Welly", lastName: "Shen" },
onSubmit: (values, { reset }) => reset(),
onReset: (values, options /* Useful helpers */, e) =>
console.log("onReset: ", values), // Triggered on form reset
});
return (
<form ref={form}>
<Field label="First Name" id="first-name" name="firstName" />
<Field label="Last Name" id="last-name" name="lastName" />
<input type="submit" />
</form>
);
};

Reset Form Manually#

We can also lazily set (or update) the form's default values by the reset method.

Edit RCF - Lazy Default Values

import { useEffect } from "react";
import { useForm } from "react-cool-form";
const App = () => {
const { form, reset } = useForm({
onReset: (values, options, e) => console.log("onReset: ", values), // Triggered on form reset
});
useEffect(async () => {
const data = await fetchData("https://form-values"); // Returns { firstName: "Welly", lastName: "Shen" }
reset(data);
}, [reset]);
const handleFormReset = async () => {
const data = await fetchData();
reset(data);
};
return (
<form ref={form}>
<Field label="First Name" id="first-name" name="firstName" />
<Field label="Last Name" id="last-name" name="lastName" />
<input type="submit" />
</form>
);
};

Reset Button (not recommended)#

As the UX research mentioned: "Most Web forms would have improved usability if the Reset button was removed." But in case you need it, React Cool Form supports the onreset internally. All we need to do is to provide an <input type="reset"> to the user.

import { useForm } from "react-cool-form";
const App = () => {
const { form, reset } = useForm({
onReset: (values, options, e) => console.log("onReset: ", values), // Triggered on form reset
});
return (
<form ref={form}>
{/* ... */}
<input type="reset" />
</form>
);
};