Top React Hooks — Form, Layout, and Async

Image for post
Image for post
Photo by Elizeu Dias on Unsplash

Hooks contains our logic code in our React app.

We can create our own hooks and use hooks provided by other people.

In this article, we’ll look at some useful React hooks.

React Hook Form

React Hook Form is a useful form library to let us add forms to a React app easily.

To install it, we run:

Then we can use it by writing:

We create our form with the inputs.

And we use the useForm hook to return some functions and objects we cause.

register lets us register our input so that we can use React Hook Form to do validation and handle input values.

errors has the errors for each field.

handleSubmit is a function that lets us handle submissions.

It takes a callback which we create to get the form data and do something with it.

The data parameter in onSubmit has the inputted data.

The register function takes an object with the pattern and required properties.

pattern has the validation pattern.

required indicates whether the field is required.

react-hook-layout

The react-hook-layout library lets us create layouts with a hook.

To install it, we can run:

or:

Then we can use it by writing:

We use the defineSlots function to create our slots for the layout.

The arguments are the slot component names.

Then we can use the useLayout hook to create the Layout component to wrap around the slots.

react-hooks-async

The react-hooks-async library lets us make HTTP requests easily.

To install it, we run:

Then we can use it by writing:

We created the fetchName function which takes an object with the signal property and parameters we pass in.

signal is the abort signal.

name is the parameter we want to pass in.

It returns a promise which resolves to the response data.

Then we can use the useAsyncTask hook with the fetchName function to return the task object.

We use this with the useAsyncRun hook with the argument we want to pass in.

Then task object has the pending , error , result , and abort properties.

pending indicates whether the result is pending.

error has any errors which come up.

result has the response body.

abort has the abort signal.

Image for post
Image for post
Photo by Maarten van den Heuvel on Unsplash

Conclusion

React Hook Form lets us create forms easily.

react-hook-layout lets us create layouts.

The react-hooks-async library lets us run async code with ease.

Written by

Web developer. Subscribe to my email list now at http://jauyeung.net/subscribe/. Email me at hohanga@gmail.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store