DEV Community 👩‍💻👨‍💻

Ridha Mezrigui
Ridha Mezrigui

Posted on

React Hooks : How to manage your form state dynamically using a custom hook

hello community,

in this post i'm gonna show you how to manage your form state dynamically using a custom hook in few steps.

So first what are hooks?

Hooks are a new addition in React 16.8 let you use state and other React features without writing a class and the funniest thing is that you can build your own custom Hook.
Custom Hook is a mechanism to reuse stateful logic.

1.create a react-app :

npx create-react-app manage-form-state
Enter fullscreen mode Exit fullscreen mode

2.build our form:

in the app.js component

import React from 'react';

function App() {

  const formHandler = e => {
    e.preventDefault();
    console.log('form handler');
  }

  return (
    <div className="App">
      <form onSubmit={formHandler}>
        Name : <input type='text' /> <br />

        Email : <input type='email' /><br />

        Address : <input type='text' /><br />

        Phone : <input type='text' /><br />

        Password : <input type='password' /><br />

        <input type='submit' value='Submit' />
      </form>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

3.create a formReducer function :

//form-reducer.js
const formReducer = (state, action) => {
    switch (action.type) {
        case 'INPUT_CHANGE':
            return {
                ...state,
                inputs: {
                    ...state.inputs,
                    [action.inputId]: action.value
                }
            }
        default:
            return state;
    }
}

export default formReducer;
Enter fullscreen mode Exit fullscreen mode

4.create our 'useForm' custom hook :

//form-hook.js
import { useReducer } from 'react';
import formReducer from  './form-reducer';

export const useForm = (initialInputs) => {
    const [formState, diaspatch] = useReducer(formReducer, {
        inputs: initialInputs
    });

    const inputHandler = (id, value) => {
        diaspatch({
            type: 'INPUT_CHANGE',
            value: value,
            inputId: id
        })
    }

    return [formState, inputHandler];
};
Enter fullscreen mode Exit fullscreen mode

5.implement the 'useForm' logic in our form :

first we have to import our useForm hook and initialize the state

import React from 'react';
import './App.css';
import { useForm } from './form-hook';

function App() {
  const [formState, inputHandler] = useForm({
    name: '',
    email: '',
    address: '',
    phone: '',
    password: ''
  });
Enter fullscreen mode Exit fullscreen mode

now we need another function that will call the inputHandler when the input value change

const changeHandler = e  => {
     const {id,value} = e.currentTarget;
     inputHandler(id,value);
  }
Enter fullscreen mode Exit fullscreen mode

finally we are ready to update our form

 const { name,email,address,phone,password } = formState.inputs;
  return (
    <div className="App">
      <form onSubmit={formHandler}>
        Name : <input type='text' id='name' 
                     value={name} 
                     onChange={changeHandler} /> <br />

        Email : <input type='email' id='email' 
                       value={email} 
                       onChange={changeHandler} /><br />

        Address : <input type='text' id='address' 
                         value={address}
                          onChange={changeHandler} /><br />

        Phone : <input type='text' id='phone' 
                       value={phone} 
                       onChange={changeHandler} /><br />

        Password : <input type='password' id='password' 
                          value={password} 
                          onChange={changeHandler} /><br />

        <input type='submit' value='Submit' />
      </form>
    </div>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Let's Get Wacky


Use any Linode offering to create something unique or silly in the DEV x Linode Hackathon 2022 and win the Wacky Wildcard category

Join the Hackathon <-