Top React Hooks — Data Structures

Image for post
Image for post
Photo by Efe Kurnaz 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.

useMap

The useMap hook lets us track key-value pairs.

To use it, we can write:

The useMap hook takes an object and returns an array that has the state object and another object with methods to let us modify the state object.

map has the map state object itself

set takes a key and value as arguments and put them into map .

setAll lets overwrite the existing value of map with another one.

remove lets us remove a property with a given key from map .

reset will reset the state object to the initial value, which is what we passed into the useMap hook.

useSet

The useSet hook lets us get and manipulate a set.

We can add things if they don’t exist.

For instance, we can write:

We have the useSet hook with a set passed in to set the initial value of the returned set.

It returns an array with 2 entries.

The first is the set , which is the set itself.

The 2nd is an object with various methods to change the set.

add lets us add an item to the set.

has lets us check whether something is in the set.

remove lets us remove an item from the set.

toggle lets us toggle on an off an item in the set.

reset resets the set to the initial value.

useQueue

We can use the useQueue hook to create a simple FIFO queue.

For example, we can write:

to create a queue and use it.

The useQueue hook returns an object with various properties.

The add function lets us add an entry to the queue.

remove lets us remove the last entry from the queue.

first returns the first entry of the queue.

last returns the last entry of the queue.

size returns the size of the queue.

Conclusion

React-use lets us create states with various data structures, including maps, sets, and queues.

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