Creating React Forms With Custom Hook

Creating React Forms With Custom Hook

Feb 8, 2023ยท

2 min read

Play this article

In any application we are developing, we always need a form and that could be easy to implement with react using useState, but in cases where we need more than one form, it becomes hectic and stressful because we always need to call an onChange function and most times a reset button.

The Form is one of the components that do the same thing in our application and this article would be focusing on using a custom hook to fix the repetition of form creation.

In this example, I will explain how we can use the custom hook to save time and also make our work easier.

Take a look at the code below:

Screenshot 2022-10-13 at 13.00.28.png

The initialValue above is the default value whenever we call this input state in our component.

The handleChange function is used to change the value of the input.

The resetInput function is used to change the input back to its original state.

After that, we return them in an array. note: You can also return them in an object.

Anytime we call this custom hook function, we have to pass the input, the onChange function that will update the state, and the reset function.

For example,

Screenshot 2022-10-13 at 13.12.07.png

With this method, not only is our code shorter but now if we want to have multiple forms in our application, they can now rely on the useInputState.

Pure Source India Glass Jar Container, with Air Tight Lid, Suitable For Kitchen Stuff, Capacity-1 Ltr, ( 6 Pcs Pack)

Did you find this article valuable?

Support ZordCoder by becoming a sponsor. Any amount is appreciated!