Logo

dev-resources.site

for different kinds of informations.

React custom hooks to update form data

Published at
2/26/2021
Categories
react
customhooks
reacthooks
frontend
Author
nabaraj
Author
7 person written this
nabaraj
open
React custom hooks to update form data

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.

customhooks Article's
29 articles in total
Favicon
Mastering Navigation Control in React with useCallbackPrompt and useBlocker 🚦
Favicon
Custom Hooks in React: Reusing Logic Across Components
Favicon
Fixing UI Update Issues with Custom Hooks in React
Favicon
Custom Hooks in React: A Guide to Creation and Usage
Favicon
React: leveraging custom hooks to extract reusable logic
Favicon
Custom Hooks
Favicon
Custom Hooks in React
Favicon
Mobile Orientation (React-Native)
Favicon
Reusing Logic in React with Custom Hooks: a Practical guide
Favicon
Harnessing Firebase in React with Custom Hooks: A Practical Guide
Favicon
Building Powerful React Components with Custom Hooks
Favicon
React Custom Hooks (useNetworkStatus)
Favicon
React Custom Hooks (useMediaPermission)
Favicon
React Custom Hooks (useDebounce)
Favicon
How to Create a Counter App with useReducer and Custom Hooks
Favicon
How to create custom Hooks in React.Js?
Favicon
React Slideshow Component with autoplay, fullscreen mode and expand all
Favicon
React Portals: create and open modals with keyboard keys
Favicon
Learn Something on React JSX and Hooks
Favicon
How to create Tabs in ReactJs using Hooks ?
Favicon
Simple hook to handle featue flags
Favicon
React custom hooks to update form data
Favicon
useIpAdrress()
Favicon
Custom hook useScroll.tsx :: React TypeScript
Favicon
useQuery() with React Router Dom
Favicon
React Custom Hooks
Favicon
useGeoPosition Hook - A Custom React Hook to grab latitude and longitude from a given address.
Favicon
`useBackButton` hook to handle back button behavior in React Native
Favicon
Form in Modal using React hooks – mistakes and lesson learnt

Featured ones: