Published: September 23 2021

React Hook Form - Reset form with default values and clear errors

Tutorial built with React 17.0.2 and React Hook Form 7.15.3

This is a quick example of how to reset a React Hook Form with default values and clear form validation error messages.

The solution is to use the reset() function from the React Hook Form library, if you execute the function without any parameters (reset()) the form is reset to its default values, if you pass an object to the function it will set the form with the values from the object (e.g. reset({ firstName: 'Bob' })).

Reset and form default values

Calling the reset function with an object (e.g. reset({ firstName: 'Bob' })) will also update the defaultValues of the form with the values from the object, so subsequent calls to reset() (without params) will use the new default values.


Example React Hook Form with Reset

This is an example React Hook Form with a few basic user fields to demonstrate resetting a form to its default values and clearing validation messages. All fields are required so to test it make any of them empty and click submit, then click reset to bring back the default values and clear the validation messages.

(See on StackBlitz at https://stackblitz.com/edit/react-hook-form-set-reset-form-example)


App Component with React Hook Form

This is the code from the above example React App component that contains a form built with React Hook Form.

Form validation rules are defined with the Yup schema validation library and passed with the formOptions to the React Hook Form useForm() function, for more info on Yup see https://github.com/jquense/yup.

A pair of useEffect() hooks are used to simulate an API call and to load the user data into the form, the form values and default values are set in the second useEffect() hook with a call to the React Hook Form reset function (reset(user)).

The reset button at the bottom of the form calls the reset() function without parameters to reset the form back to its default values and to clear any validation error messages from the form.

import React, { useState, useEffect } from 'react';
import { useForm } from "react-hook-form";
import { yupResolver } from '@hookform/resolvers/yup';
import * as Yup from 'yup';

function App() {
    // form validation rules 
    const validationSchema = Yup.object().shape({
        title: Yup.string()
            .required('Title is required'),
        firstName: Yup.string()
            .required('First Name is required'),
        lastName: Yup.string()
            .required('Last name is required')
    });
    const formOptions = { resolver: yupResolver(validationSchema) };

    // get functions to build form with useForm() hook
    const { register, handleSubmit, reset, formState } = useForm(formOptions);
    const { errors } = formState;

    // user state for form
    const [user, setUser] = useState(null);

    // effect runs on component mount
    useEffect(() => {
        // simulate async api call with set timeout
        setTimeout(() => setUser({ title: 'Mr', firstName: 'Frank', lastName: 'Murphy' }), 1000);
    }, []);

    // effect runs when user state is updated
    useEffect(() => {
        // reset form with user data
        reset(user);
    }, [user]);

    function onSubmit(data) {
        // display form data on submit
        alert('SUCCESS!! :-)\n\n' + JSON.stringify(data, null, 4));
        return false;
    }

    return (
        <div className="card m-3">
            <h5 className="card-header">React Hook Form - Reset Form with Default Values Example</h5>
            <div className="card-body">
                {user &&
                    <form onSubmit={handleSubmit(onSubmit)}>
                        <div className="form-row">
                            <div className="form-group col">
                                <label>Title</label>
                                <select name="title" {...register('title')} className={`form-control ${errors.title ? 'is-invalid' : ''}`}>
                                    <option value=""></option>
                                    <option value="Mr">Mr</option>
                                    <option value="Mrs">Mrs</option>
                                    <option value="Miss">Miss</option>
                                    <option value="Ms">Ms</option>
                                </select>
                                <div className="invalid-feedback">{errors.title?.message}</div>
                            </div>
                            <div className="form-group col-5">
                                <label>First Name</label>
                                <input name="firstName" type="text" {...register('firstName')} className={`form-control ${errors.firstName ? 'is-invalid' : ''}`} />
                                <div className="invalid-feedback">{errors.firstName?.message}</div>
                            </div>
                            <div className="form-group col-5">
                                <label>Last Name</label>
                                <input name="lastName" type="text" {...register('lastName')} className={`form-control ${errors.lastName ? 'is-invalid' : ''}`} />
                                <div className="invalid-feedback">{errors.lastName?.message}</div>
                            </div>
                        </div>
                        <div className="form-group">
                            <button type="submit" className="btn btn-primary mr-1">Submit</button>
                            <button type="button" onClick={() => reset()} className="btn btn-secondary">Reset</button>
                        </div>
                    </form>
                }
                {!user &&
                    <div className="text-center p-3">
                        <span className="spinner-border spinner-border-lg align-center"></span>
                    </div>
                }
            </div>
        </div>
    )
}

export { App };

 


Need Some React Hook Form Help?

Search fiverr for freelance React Hook Form developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by