React 18 Set / Reset Form Values with Hook Form Tutorial

Last Updated on by in React JS

Form is the heart of every application; it helps gather information from the user directly.

As far as React is concerned, creating a form is super easy using functional component and React useState, and useEffect hooks.

However, managing state, form values, validation is a little bit difficult.

What if I tell you there is a library called React Hook Form?

The hook form module keeps the form complexities at bay, and it makes working with form super easy and fun.

This extensive guide will teach you how to set form input values in React app using the React hooks (useEffect and useState) and react hook form module.

React hook form offers some handy APIs that make your life easy.

We will demonstrate how to use register, handleSubmit, and reset APIs to manage the form data dynamically.

reset(): This method is handy and allows resetting the entire form state or a small part of the form.

We will use this API to reset the form values in this react hook form example.

register(): This method lets you register an input or select element and lay down the foundation of validation rules to React Hook Form. All validation rules are based on the HTML standard and support custom validation.

handleSubmit(): This method obtains the form data if form validation is passed.

Let go through all the procedures to set form values of a React form in functional component using react hooks.

How to Use React Hook Form and React Hooks to Set and Reset Form Values

  • Step 1: Create New Application
  • Step 2: Install Bootstrap Library
  • Step 2: Add React Hook Form Package
  • Step 3: Create Form with Hooks Form
  • Step 4: Render Form in View
  • Step 5: Run Development Server

Create New Application

Start with creating a new React application, on your terminal’s console type the command and run command.

npx create-react-app react-proxima

Now, app is installed, move into the project directory.

cd react-proxima

If you already have project set up then jump on to the next step.

Install Bootstrap Library

We want to slash down the time we are going to devote to form UI creation.

You can add the given command on the console and press enter to begin bootstrap module installation.

npm install bootstrap --legacy-peer-deps

Add React Hook Form Package

In this step, you have to again type the given command on the terminal and execute the command to install react hook form package.

npm install @hookform/resolvers --legacy-peer-deps

Create Form with Hooks Form

In your project directory, you have to create a new components/ folder. Also, you require to create the UserForm.js file.

import React, { useState, useEffect } from 'react'
import { useForm } from 'react-hook-form'

export default function UserForm() {
  const { register, handleSubmit, reset } = useForm()

  const [user, inituser] = useState(null)

  useEffect(() => {
    setTimeout(
      () =>
        inituser({
          name: 'Tom Holland',
          email: 'spidy@mcu.com',
          mobile: '202 555 0191',
        }),
      800,
    )
  }, [])

  useEffect(() => {
    reset(user)
  }, [user])

  function onSubmit(dataRes) {
    console.log(dataRes)
    return false
  }

  return (
    <div className="container mt-3">
      <h2>React Set Form Values using React Hook Form Example</h2>

      {user && (
        <form onSubmit={handleSubmit(onSubmit)} className="mt-3">
          <div className="form-group mb-3">
            <label>Name</label>
            <input
              type="text"
              name="name"
              {...register('name')}
              className="form-control"
            />
          </div>

          <div className="form-group mb-3">
            <label>Email</label>
            <input
              type="email"
              name="email"
              {...register('email')}
              className="form-control"
            />
          </div>

          <div className="form-group mb-3">
            <label>mobile</label>
            <input
              type="text"
              name="mobile"
              {...register('mobile')}
              className="form-control"
            />
          </div>

          <div className="d-grid">
            <button type="submit" className="btn btn-primary mb-2">
              Submit
            </button>

            <button
              type="button"
              onClick={() =>
                reset({
                  name: '',
                  email: '',
                  mobile: '',
                })
              }
              className="btn btn-danger"
            >
              Reset
            </button>
          </div>
        </form>
      )}
      {!user && (
        <div className="text-center p-3">
          <span className="spinner-border spinner-border-sm align-center"></span>
        </div>
      )}
    </div>
  )
}

Render Form in View

Now, we have completed almost everything, and we can not render the user form component in the browser’s view.

For, that we need to add and import the user component in App.js file.

import React from 'react'
import UserForm from './components/UserForm.js'
import 'bootstrap/dist/css/bootstrap.min.css'

function App() {
  return (
    <div>
      <UserForm />
    </div>
  )
}

export default App;

Run Development Server

Last, we have to start the react application, we can do it by starting the app development server.

Head over to console, type following command and hit enter to run the app.

npm start

Here is the url, that you can use to check the set form values.

http://localhost:3000

You can see the default values of form that we set using hook form api.

React Set / Reset Form Values with Hook Form and Hooks Tutorial

Summary

I have tried to shed light on every concept with utmost simplicity from form input values and reset form context.

This article started with app creation, package installation, and component setup.

Eventually, we learned how to set up the form and multiple form values using hook form in React js app.

To manage the behavior of the component, we used the useState and useEffect hooks; we believe you will love our efforts.