Programming Blog

React Custom Hook

July 04, 2020

What is the use of custome hooks ?

A custom hook is basically a JS function which helps to share logic between two or more components. It’s like a alternative to render props and higher-order components which we used share stateful logic between components.

For defining a custome hook we use JS function whose name start with “use”. Custom hook can also use other hook if required.

How to implement?

For this example implement simple form to get user first and last name.

First we implement form in normal approach

  1. Create a file UserForm.js and define a simple functional component.
  2. import useState and create two variables

import useState and create two variables

  1. Add JSX for from

form JSX

  1. Now we change this input elements into controlled elements and add onSubmit handler to form.

added handlers

  1. Now implement submitHandler function

    const submitHandler = e =>{
        e.preventDefault()
        alert(`Hello ${firstName} ${lastName}`)
    }
  2. Final code

final code

  1. Import this component into App.js and run with npm start

Now we implement hook

for that we have to encapsulate the input elements bind value and onChange attribute behaviour of input element.

  1. Create a file useInput.js and add functional component and import useState hook
  2. Create state variable to track the input field value and set default value to initialValue which will be pass as parameter.

useInput nitial

  1. Now we define function to reset values to initial values and also one object with two properties value and onChange. onChange is a function which gets event as parameter and set the value to target value.
  2. finally we return value , defined object and reset function.

useInput final

next task is to use this in our form

  1. Now in UserForm.js import useInput.js i.e. our useInput().
  2. Next we replace useState hook call for firstName with useInput custom hook. here we pass inital value as empty as we pass before. useInput() return three values that are value, bind object and reset function so we first destructure them.

    const [firstName, bindFirstName, restFirstName] = useInput(’ ‘)

NOTE : delete useState() for firstName
  1. do same for last name.

    const [lastName, bindLastName, restLastName] = useInput(”)

  2. as from code we see firstName and lastName are used in submit handler , we have to use remaining two but where?
  3. first we replace value and onChange attribute of firstName input element with bindFirstName like this

    <input
       {...bindFirstName}
        type="text"
      />
  4. do same for lastName.
  5. last use resetFirstName() and restLastName() inside submit handler.

final UserForm

from above example we used custom hook concept to share the logic of assinging a value and onChange handler to each input element.


Akshay Jadhav

Written by Akshay Jadhav Mobile application and Full stack web-developer My PortfolioYou can contact me onInstagram