Published:

React Hook Form - Submitting (Loading) Spinner Example

Tutorial built with React 17.0.2 and React Hook Form 17.15.2

This is a quick example to show how to display a loading spinner and disable the form submit button while a form is submitting with the React Hook Form library.

The main thing to remember (which I often forget) is that you have to return a Promise from the form submit handler function for this to work, otherwise the React Hook Form formState.isSubmitting property will always be false. For example if your app sends an HTTP request on submit using fetch() or axios(), the Promise returned from that function must be returned by the submit handler function to set formState.isSubmitting to true.


Example React Hook Form with Spinner on Submit

This is an example React Hook Form with only a submit button to demonstrate how to show a loading spinner on submit using the form state isSubmitting property.

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


App Component with React Hook Form

This is the code from the above example React App component, the submit handler function (onSubmit()) returns a Promise object that resolves after 2 seconds, the React Hook Form isSubmitting property is true and the loading spinner is displayed until the Promise is resolved, also the submit button is disabled while the form is submitting.

import React from 'react';
import { useForm } from "react-hook-form";

function App() {
    // get functions to build form with useForm() hook
    const { handleSubmit, formState } = useForm();
    const { isSubmitting } = formState;

    function onSubmit(data) {
        // return promise that resolves after 2 seconds
        return new Promise(resolve => {
            setTimeout(() => {
                resolve();
            }, 2000);
        });
    }

    return (
        <div className="card m-3">
            <h5 className="card-header">React Hook Form - Submitting Spinner Example</h5>
            <div className="card-body">
                <form onSubmit={handleSubmit(onSubmit)}>
                    <button disabled={isSubmitting} className="btn btn-primary mr-1">
                        {isSubmitting && <span className="spinner-border spinner-border-sm mr-1"></span>}
                        Submit
                    </button>
                </form>
            </div>
        </div>
    )
}

export { App };

 


Need Some React Hook Form Help?

Search fiverr to find help quickly from experienced React Hook Form developers.


Exclusive Semrush Special Offer

FREE 14-day PRO trial to Semrush is available to visitors of this blog. Check your website health quickly and easily with the Semrush all-in-one site auditing tool, eliminate technical SEO issues and optimize your website's speed and performance.


Supported by