DEV Community

loading...

React custom hooks to update form data

Nabaraj saha
・3 min read

Photo by Efe Kurnaz on Unsplash
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 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

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>
  )
}

Enter fullscreen mode Exit fullscreen mode

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

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;
Enter fullscreen mode Exit fullscreen mode

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

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>
  )
}
Enter fullscreen mode Exit fullscreen mode

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.

Discussion (0)