Site icon RemoteStack

React Hook Form Set & Update Form Values with useEffect Hook

React useEffect set form values tutorial; In this example, we will show you how to set up a form in React application using hook form, react useState, and useEffect hooks.

On top of that, you will understand how to set up form input field values in the useEffect hook after the asynchronous data is rendered.

React hook forms library is incredible, especially for those who love to create various functionalities in React.

We are going to shed light on React form component. The form is an essential component in any application. It provides an eloquent way to collect information from the users.

If you come from React background, then you must be aware of how challenging it might be to deal with forms. Thanks to React hook form package. You can efficiently manage the form state, validation, errors. Ideally, it makes all the tedious form-related work so much easy.

How to Set Form Input Control Values in React using useEffect Hook

Build React App

You must have a React application to accumulate all the code to create the feature you want.

Get into the terminal and run the suggested command.

npx create-react-app react-tiny-form

Furthermore, enter into the project folder.

cd react-tiny-form

Install Hook Form Library

Here is how you put the given command on the console to install the hook form package. We are also installing the resolvers library.

npm install @hookform/resolvers

Set Up Form in Component

To set up the form values in React side effect hook first requires a form to be created.

So, without wasting much time, quickly create the components/SimpleForm.js file.

As told before, we will use the hook form library to build the form, make sure to import the useForm module from ‘react-hook-form’ package.

Also, import the useState and useEffect hooks before the hook form plugin.

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

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

  const [student, initStudent] = useState(null)

  useEffect(() => {
    setTimeout(
      () =>
        initStudent({
          name: 'Little Johnny',
          email: 'lil@johnny.com',
          grade: '3rd',
        }),
      1200,
    )
  }, [])

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

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

  return (
    <div>
      <h2 className="mb-3">
        React Initiate Form Values in useEffect Hook Example
      </h2>

      {student && (
        <form onSubmit={handleSubmit(onFormSubmit)}>
          <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>Grade</label>
            <input
              type="text"
              name="grade"
              {...register('grade')}
              className="form-control"
            />
          </div>

          <button type="submit" className="btn btn-dark">
            Send
          </button>
        </form>
      )}
      {!student && (
        <div className="text-center p-3">
          <span className="spinner-border spinner-border-sm align-center"></span>
        </div>
      )}
    </div>
  )
}

We first set the student state in the form using useState.

There are two useEffect hooks; the first use effect invokes when the component the mounts.

At the same time, it initiates the asynchronous API call through the set timeout method.

The second use effect hooks execute when the student state is updated.

Lastly, when you click on the form submit button, you can see the form data on the browser’s console screen.

Add Component in App Js

If you are not using the routing mechanism, then to render the component in the view requires you to import the newly built component in App.js file.

This is how you set up the SimpleForm component in the app js file.

import React from 'react'

import SimpleForm from './components/SimpleForm'
import 'bootstrap/dist/css/bootstrap.min.css';


export default function App() {
  return (
    <div className="container mt-4">
      <SimpleForm />
    </div>
  )
}

Run React Project

Now, in this last step we are going to start the react project. React made it simpler, you can start the react app using the following command.

npm start

You may use the given localhost url to test the app. Put it int the browser, and check the outcome.

http://localhost:3000

Conclusion

In this guide, we shared how to create a simple form, set the form values or personal data using the React Hook Form, React useState, useEffect hooks. We showed you in the example how to initiate the form values after the form data is loading asynchronously.

Exit mobile version