Top React Hooks — Forms and Forward Refs

Image for post
Image for post
Photo by Heather Lo 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-use

The react-use library is a big library with many handy hooks.

useMethods

The useMethods hook is a simpler useReducer hook implementation.

It lets us cache states so it’s useful for using complex computations.

For instance, we can write:

We created the countMethods function with the methods we can use to manipulate our state .

It returns the state as we want to by returning an object with various methods.

reset returns the initial state.

increment returns a state with count increased by 1.

decrement returns a state with count decreased by 1.

We passed the countMethods function into the useMethods hook along with the initialState .

Then that returns the state and the methods object that has the methods returned by countMethods .

We then called them when we click the buttons.

useEnsuredForwardedRef

The useEnsuredForwardedRef hook letrs us forward refs to a child component.

For instance, we can write:

to use the hook.

We just pass in a ref to the useEnsuredForwardRef hook and it’ll return ensuredForwardRef .

It’ll never be undefined , so we can use it as we do in the useEffect callback.

useFormless

React-useFormless is a simple library that lets us create forms with a simple hook.

We can install it by running:

or

Then we can use it by writing:

We have the options object with the options.

initialValues has the initial values of the form.

validate is a function that returns an error object after validation.

The returned object should have the keys with the input names and values being the error message.

onError , onSuccess and onSubmit are handlers that are run when those events are emitted.

We pass in the whole object to the useFormless hook.

It returns an object with the variables we can use in our form.

inputProps pass in the input elements.

onSubmit is the submit handler.

errors has the error messages.

values has the input values for each field.

Conclusion

React-use is a versatile hooks library.

React-useFormless lets us create forms easily with our React app.

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