This week I’m working at getting a multi-part form up and running on the frontend using React. While investigating how to do this I ran across useForm(), a custom hook for React to interact with data from a form. The useForm() is like an abstracted version of the useState() which allow us to handle references to inputs more efficiently, by have a single object with all the data from the form. Things like handle submits and errors can be managed without having to create additional useStates and functions to carry out this work.
With what I knew about useState() my code repeated the scheme of my database, once for inputs I needed and then again for error message, and one last time I was ready to submit. Then a handlechange() function was needed to update my form object with new user input as well as validate and update the error messages. If I continued this trend with this new phase of the project things were going to look cluttered.
By using useForm() things changed for the better. You simple decompose useForm() as follows:
const { register, setError, formState: { errors } } = useForm();
Then you can label the inputs with the register object as follows:
<input {…register(“test”)} />
If you have any error messages you can place them underneath with a paragraph html label:
{errors.test && <p>{errors.test.message}</p>}
With the setError function you can then trigger the errors if some validation logic fails.
Now, I’ve seen tutorials which do not eliminate the need for useState(), which is used to store the data gathered by useForm() and its function handleSubmit(). However the documentation for useForm() show that it comes with formState(), which stores the inputs of the form. This leads me to think that useState() might still be used as individuals are more familiar with this native React feature than this custom offering. Honestly I’m impressed with this React Hook and I expect it will come in handy when trying to get this split form running.
If you’d like to look at sample code, like the lines I provided above as well as further documentation regarding useForm() go to their website at:
https://react-hook-form.com/api/useform
CRUD application would seem to be the best candidates for this custom hook so if you happen to be working on one and are using React, seriously take a look at this.
Leave a Reply