Top React Hooks — Data Types

Image for post
Image for post
Photo by Kit Suman 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.

useToggle

The useToggle hook lets us create a boolean state that we can toggle with a function.

To use it, we can write:

useToggle takes an argument for the initial value of the toggle.

It returns the on state with the boolean.

And toggle lets us toggle the value or set on with a specific value.

useCounter

The useCounter hook lets us create a numeric state with functions to set or reset the value.

For instance, we can write:

We call the useCounter hook to return an array with various things.

The argument is the initial value.

val has the current value of the number state.

inc is the function to increment val .

dec is the function to decrement val .

set is the function to set val to a specific value.

reset resets val to the initial value.

We can also set the maximum and minimum values that val can take.

For example, we can write:

The 2nd argument of useCounter is the maximum value of val .

The 3rd argument is the minimum value of val that it can take.

useList

The useList hook lets us create a state from an array and manipulate it.

To use it, we can write:

We call the useList hook with an initial array as the argument.

It returns an object with various properties and the array itself.

list has the value of the array.

set lets us set the array to a different array.

push lets us append an entry to the list array.

insertAt lets us insert an element to the list array.

update lets us update a list entry.

updateFirst updates the first entry of list.

upsert lets us insert or update an entry of list.

sort lets us sort our the list array.

filter filters the the list array.

removeAt removes a list entry with the given index.

clear empties the list array.

reset resets the list array to the initial value.

Conclusion

The react-use library lets us create a toggle, number, and list state we can manipulate easily.

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