React custom hooks to update form data
Tags: react, customhooks, reacthooks, frontend
Published: 2021-02-26 18:06:04

![Photo by Efe Kurnaz on Unsplash](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/547hqbvsdacvs58mb0ip.png)
I tried to search an image which can show the purpose of react custom hooks. I found this after searching sometimes. It looks like to me sharing same resource which is the purpose of react custom hooks. Official custom hooks page can be found [here](https://reactjs.org/docs/hooks-custom.html) to get more clarity of defination and purpose. Custom hooks maintain separate state  and effects inside the component fully isolated.

Assuming you are familiar with React Hooks such as useState, useEffect, useContext, etc. What I am trying to show here is a basic custom hooks to update form fields values. In an application we may have multiple forms and we may need to maintain a state object to store the values of form fields(Make sense if we are not using any third party form library). Initially I was writing separate logics for each form to update. This update can be initialize with default/prepopulated values or update on change of each fields.

What I was doing before custom hooks as below.

__Some basic login form__
 ```javascript
import { useState } from 'react';

export default function Loginpage() {

  const [formData, setFormData] = useState({ email: '', password: '' });

  function changeField(e){
    let name = e.target.name;
    let value = e.target.value;
    let formObject = { ...formData };
    setFormData({ ...formObject, [name]: value });
  }
  return (
    <div className="container" style={{ maxWidth: "480px" }}>
      <div className="card shadow mt-5">
        <div className="card-body">
          <form className="form-horizontal" onSubmit={checkLogin}>
            <fieldset>
              <legend>Login Form</legend>
              <div className="form-group">
                <label className="control-label" htmlFor="textinput">Email</label>
                <div className="">
                  <input id="email" onChange={changeField} name="email" type="text" placeholder="Enter your email" className="form-control input-md" required="" />
                </div>
              </div>
              <div className="form-group">
                <label className="control-label" htmlFor="passwordinput">Password</label>
                <div className="">
                  <input id="password" onChange={changeField} name="password" type="password" placeholder="Enter your password" className="form-control input-md" required="" />

                </div>
              </div>
              <button type="submit" className="btn btn-info btn-block" disabled={!formData.email || !formData.password}>Submit</button>
            </fieldset>
          </form>

        </div>
      </div>
    </div>
  )
}

```
I have removed the checkLogin method as this is out of the scope of this topic.

Same coding logic of updating formData will be there for other form as well. So I make the custom hooks as below code.

__useUpdateForm hook__
```javascript
import { useState } from 'react';

function useUpdateForm(initValue = {}) {
  const [formData, setFormData] = useState(initValue);

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

  const resetForm = (initialValue) => {
    let formObject = { ...formData };
    setFormData({ ...formObject, ...initialValue });
  }

  return [formData, changeField, resetForm];
  
}

export default useUpdateForm;
```
I have added one more method to reset the Form data. It was useful if we want to reset the form any point of time.

Now how my component looks like
```javascript
import { useState } from 'react';
import useUpdateForm from "./../utils/submitFormHook";
export default function Loginpage() {

  const [formData, changeField] = useUpdateForm({ email: '', password: '' });

  
  return (
    <div className="container" style={{ maxWidth: "480px" }}>
      <div className="card shadow mt-5">
        <div className="card-body">
          <form className="form-horizontal" onSubmit={checkLogin}>
            <fieldset>
              <legend>Login Form</legend>
              <div className="form-group">
                <label className="control-label" htmlFor="textinput">Email</label>
                <div className="">
                  <input id="email" onChange={changeField} name="email" type="text" placeholder="Enter your email" className="form-control input-md" required="" />
                </div>
              </div>
              <div className="form-group">
                <label className="control-label" htmlFor="passwordinput">Password</label>
                <div className="">
                  <input id="password" onChange={changeField} name="password" type="password" placeholder="Enter your password" className="form-control input-md" required="" />

                </div>
              </div>
              <button type="submit" className="btn btn-info btn-block" disabled={!formData.email || !formData.password}>Submit</button>
            </fieldset>
          </form>

        </div>
      </div>
    </div>
  )
}
```
Some extra line of code is got removed and this became common logic for other forms as well. 

__Area of improvement__
This is a very basic example for react custom hooks. Always there will be chance of improvement. Maybe we can add validation logic in this.