Using the useForm hook

Tim Rinkerman
3 min readJan 8, 2021

--

One of my favorite things about hooks is how they make programming a bit more simplistic. Take the use form hook for instance, the useForm hook. With this hook you can simplify and stream line forms within react, and cut down on some verbose typing.

To begin start by installing the hook with

Next import the hook into your program,

What I think makes this hook super useful is its built in variables of “register, handleSubmit and errors.”

First we have the register variable. What is neat about this is when adding it to a form it eliminates the need for an on change function. You simply ref it within your form line like so.

In this scenario I am actually using the input as a way to extract an image file from a users files saved locally to the machine. You can also use this for any other type of input you could imagine and set certain restrictions, think, if you wanted to create a password input and make sure it was a certain length and had certain characters.

Now that we are keeping track of what the user is inputing it is important to be able to redirect that input.

Using the handleSubmit variable attached to this hook, we can create a call back function where we pass our handleSubmit to a onSubmit (corresponding to a submit button that has been attached to the form) in order to create a data object to work with.

Our handleSubmit function will look something like this.

For now I am just console logging the data that is being passed through the function but this is great for a POST request.

The form should look something like this.

So in action we can see when we hit submit the file we’re adding is passed to our handle submit function is created into a data object that we can then manipulate. In addition, since we have the register variable in the ref section of the input we can update what we’re submitting with out having to write out a whole function.

Thanks for reading and happy coding!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response