How to Reset Form in React JS

While I was working on a React project, users needed to fill out a registration form. After submission, I wanted the form to clear all input fields for the next entry. I quickly realized that resetting forms in React isn’t as simple as it is in plain HTML.

The issue is, React’s controlled components pattern means we need to handle state properly when resetting forms. Simply using the HTML reset method isn’t enough when working with React’s state management.

In this article, I will cover four reliable methods to reset forms in React JS.

Method 1 – Use React’s useState Hook

The most common approach to handling forms in React is with controlled components using the useState hook. This method gives you complete control over the form reset process.

Here’s how I implement it in my projects:

import React, { useState } from 'react';

function UserForm() {
  const initialFormState = {
    firstName: '',
    lastName: '',
    email: '',
    message: ''
  };

  const [formData, setFormData] = useState(initialFormState);

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData({
      ...formData,
      [name]: value
    });
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    // Process form submission (e.g., API call)
    console.log('Form submitted:', formData);

    // Reset the form
    setFormData(initialFormState);
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label>First Name:</label>
        <input
          type="text"
          name="firstName"
          value={formData.firstName}
          onChange={handleChange}
        />
      </div>

      <div>
        <label>Last Name:</label>
        <input
          type="text"
          name="lastName"
          value={formData.lastName}
          onChange={handleChange}
        />
      </div>

      <div>
        <label>Email:</label>
        <input
          type="email"
          name="email"
          value={formData.email}
          onChange={handleChange}
        />
      </div>

      <div>
        <label>Message:</label>
        <textarea
          name="message"
          value={formData.message}
          onChange={handleChange}
        />
      </div>

      <button type="submit">Submit</button>
    </form>
  );
}

export default UserForm;

I executed the above example code and added the screenshot below.

Reset Form in React JS

In this example, I’m storing the form state in a formData object. After submission, I reset the form by setting formData back to its initial state. This is a clean approach that works with any form complexity.

Method 2 – Use the HTML Reset Method with useRef

Sometimes you might want to leverage the HTML form’s native reset method. This is particularly useful when working with uncontrolled components.

Here’s how I implement this approach:

import React, { useRef } from 'react';

function ContactForm() {
  const formRef = useRef(null);

  const handleSubmit = (e) => {
    e.preventDefault();

    // Get form data using FormData API
    const formData = new FormData(e.target);
    const formValues = Object.fromEntries(formData.entries());

    // Process form submission
    console.log('Form submitted:', formValues);

    // Reset the form using the native reset method
    formRef.current.reset();
  };

  return (
    <form ref={formRef} onSubmit={handleSubmit}>
      <div>
        <label>Name:</label>
        <input type="text" name="name" />
      </div>

      <div>
        <label>Email:</label>
        <input type="email" name="email" />
      </div>

      <div>
        <label>Subject:</label>
        <input type="text" name="subject" />
      </div>

      <div>
        <label>Message:</label>
        <textarea name="message"></textarea>
      </div>

      <button type="submit">Submit</button>
      <button type="button" onClick={() => formRef.current.reset()}>Clear Form</button>
    </form>
  );
}

export default ContactForm;

I executed the above example code and added the screenshot below.

How to Reset Form in React JS

In this approach, I’m using useRef to get a reference to the form element. After processing the submission, I call the native reset() method on the form. I’ve also added a separate “Clear Form” button that resets the form without submission.

Note: This method works best with uncontrolled components. If you’re using controlled components, you’ll still need to update your state.

Read Props in React JS

Method 3 – Use Formik Library

When working on larger applications, I often use Formik – a popular form library for React. It makes form handling, validation, and resetting much easier.

Here’s how I implement form reset with Formik:

import React from 'react';
import { Formik, Form, Field, ErrorMessage } from 'formik';
import * as Yup from 'yup';

function SignupForm() {
  const initialValues = {
    username: '',
    email: '',
    password: '',
    confirmPassword: ''
  };

  const validationSchema = Yup.object({
    username: Yup.string().required('Username is required'),
    email: Yup.string().email('Invalid email address').required('Email is required'),
    password: Yup.string().min(8, 'Password must be at least 8 characters').required('Password is required'),
    confirmPassword: Yup.string()
      .oneOf([Yup.ref('password'), null], 'Passwords must match')
      .required('Confirm password is required')
  });

  const handleSubmit = (values, { resetForm }) => {
    // Process form submission
    console.log('Form submitted:', values);

    // Reset the form
    resetForm();
  };

  return (
    <Formik
      initialValues={initialValues}
      validationSchema={validationSchema}
      onSubmit={handleSubmit}
    >
      {({ resetForm }) => (
        <Form>
          <div>
            <label htmlFor="username">Username</label>
            <Field type="text" id="username" name="username" />
            <ErrorMessage name="username" component="div" className="error" />
          </div>

          <div>
            <label htmlFor="email">Email</label>
            <Field type="email" id="email" name="email" />
            <ErrorMessage name="email" component="div" className="error" />
          </div>

          <div>
            <label htmlFor="password">Password</label>
            <Field type="password" id="password" name="password" />
            <ErrorMessage name="password" component="div" className="error" />
          </div>

          <div>
            <label htmlFor="confirmPassword">Confirm Password</label>
            <Field type="password" id="confirmPassword" name="confirmPassword" />
            <ErrorMessage name="confirmPassword" component="div" className="error" />
          </div>

          <button type="submit">Sign Up</button>
          <button type="button" onClick={() => resetForm()}>Reset</button>
        </Form>
      )}
    </Formik>
  );
}

export default SignupForm;

I executed the above example code and added the screenshot below.

Reset Form in React JS Formik Library

Formik provides a convenient resetForm function in its submission handler. I can also access this function directly from render props to create a dedicated reset button. This approach has the advantage of also resetting any validation errors that might be displayed.

Read State in React JS

Method 4 – Use React Hook Form

Another excellent form library I use in my projects is React Hook Form. It’s performance-focused and has a simpler API than Formik in some cases.

Here’s how I implement form reset with React Hook Form:

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

function OrderForm() {
  const { register, handleSubmit, formState: { errors }, reset } = useForm();

  const onSubmit = (data) => {
    // Process form submission
    console.log('Order submitted:', data);

    // Reset the form
    reset();
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <div>
        <label>Product Name:</label>
        <input {...register('productName', { required: 'Product name is required' })} />
        {errors.productName && <p className="error">{errors.productName.message}</p>}
      </div>

      <div>
        <label>Quantity:</label>
        <input 
          type="number" 
          {...register('quantity', { 
            required: 'Quantity is required',
            min: { value: 1, message: 'Minimum quantity is 1' }
          })} 
        />
        {errors.quantity && <p className="error">{errors.quantity.message}</p>}
      </div>

      <div>
        <label>Shipping Address:</label>
        <textarea {...register('address', { required: 'Address is required' })} />
        {errors.address && <p className="error">{errors.address.message}</p>}
      </div>

      <div>
        <label>Payment Method:</label>
        <select {...register('paymentMethod', { required: 'Payment method is required' })}>
          <option value="">Select payment method</option>
          <option value="credit">Credit Card</option>
          <option value="debit">Debit Card</option>
          <option value="paypal">PayPal</option>
        </select>
        {errors.paymentMethod && <p className="error">{errors.paymentMethod.message}</p>}
      </div>

      <button type="submit">Place Order</button>
      <button type="button" onClick={() => reset()}>Clear Form</button>
    </form>
  );
}

export default OrderForm;

Read Form Validation in React.js

React Hook Form provides a reset function that we destructure from the hook. I can call this function after form submission or create a separate reset button. It efficiently resets all fields and validation states without unnecessary re-renders.

Each of these methods has its advantages. If you’re working with simple forms, the useState approach gives you full control. For more complex forms with validation, I recommend using a library like Formik or React Hook Form.

The key is to select the method that best fits your project’s requirements and your team’s familiarity with the tools.

I hope you found this article helpful.

Related tutorial:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.