Top React Hooks — State History and Validation

Image for post
Image for post
Photo by Thomas Kelley 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.

useStateValidator

We can use the useStateValidator hook to validate the state that’s changed in our app.

For instance, we can write:

to use the useStateValidator to validate the state.

We pass in the state as the first argument.

The 2nd is the NumberValidator to validate our state.

It takes the state and returns an array that has the validation state of the state .

It returns an array that’s nested in an array with the validation state.

Then we can use that anywhere we like.

useStateHistory

The useStateHistory hook lets us store a set amount of previous state values and provides handles to travel through them.

To use it, we can write:

We use the useStateWithHistory hook with a few arguments.

The first argument is the initial state.

The 2nd argument is the maximum number of items to keep.

The 3rd is the initial history.

It returns an array with the state which has the state value.

setState lets us update the state.

stateHistory has the state history.

It’s an object with various methods.

The position has the position in history.

capacity has the max capacity of the history list.

back lets us move backward in the state history.

forward lets us move forward in the state history.

go lets us go to an arbitrary position in the state history.

useMultiStateValidator

The useMultiStateValidator hook lets us invoke a validator function if any state changes.

For instance, we can write:

We have 3 states, which we can set with their own input box.

And we call useMultiStateValidator with the numbers and the NumberValidator to validate the numbers.

NumberValidator takes has an array with the array we passed in as the argument.

And it returns an array with the validation condition of all the entries.

It returns a nested array with the validation state of all the numbers.

It’ll only return true if all of them meet the criteria in the callback for every as we specified.

Conclusion

The react-use library lets us validate states and list the past values of a state in an array.

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