Top React Hooks — Managing States

Image for post
Image for post
Photo by Yuiizaa September 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-hanger

The react-hanger library comes with various hooks we can use to do various things.

To install it, we run:

We can use the useArray hook to manipulate arrays easily.

For example, we can write:

The useArray hook returns an object with various methods for changing the array.

It also returns the value property with the state of the array.

We call the push method to append something to the array.

unshift adds an item to the beginning of the array.

pop removes an item from the end of the array.

It also has the useStateful hook to let us set a state.

For example, we can write:

We use the useStateful hook as we do with the useState hook.

The useMap hook let us hold a map as a state and manipulate it.

For instance, we can write:

We use the useMap hook.

We passed an array to it with the key and value of the map.

Then it returns the value and various methods we can use to manipulate the map.

set adds an entry by passing in the key and value.

delete lets us delete an entry with the given key,

clear clears the map.

We can also pass a Map instance into the hook and get the same result.

The useSetState hook lets us manage our state as we did with the setState method in React class components.

To use it, we can write:

The useSetState hook takes an object with the states we want to manage.

The argument is the initial state.

It returns the state with all the states.

setState lets us set the state as we do with setState in React class components.

resetState will reset the state to the initial state.

Image for post
Image for post
Photo by Sophie Elvis on Unsplash

Conclusion

The react-hanger library comes with many useful hooks to manage various kinds of states.

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