Top React Hooks — State Utilities

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.

moment-hooks

The moment-hooks library is a library that comes with various utility hooks that we can use.

We can install it with:

The useDebounce hook lets us add denounce functionality to our app.

It can be used to reduce the number of times a state is updated.

For instance, we can write:

We have the useDebounce hook that takes the inputValue state.

The 2nd argument is the number of milliseconds to delay the update of the state.

The useWindowSize hook lets us get the width and height of the window.

To use it, we write:

We call the useWindowSize hook to get the window’s width and height.

Then we can use those anywhere.

The useWhyDidYouUpdate hook gets the reason why a component has been updated.

It’s useful for debugging our components.

To use it, we can write:

Then since we have the useWhyDidYouUpdate hook has been called with 'Register' and props , it’ll log the value when the props are changed.

We’ll get the old and new value logged.

Nice Hooks

Nice Hooks is a set of hooks that does various things.

To install it, we run:

Then we can use the hooks that comes with it.

The useStateCB hook lets us get and set a state.

To use it, we can write:

We use the useStateCB hook to return a getter and setter function for a state.

When we click the button, we call setCount to set the count.

doSomething is run after the state change is done.

getCount gets the count state.

The useSingleState hook is another hook that lets us get and set the state.

For instance, we can write:

useSingleState is another hook that returns that state and a setter for the state respectively.

setState takes an object to update the state.

It also takes a callback that runs when the state update is done.

Image for post
Image for post
Photo by Vidar Nordli-Mathisen on Unsplash

Conclusion

monent-hooks and Nice Hooks are libraries that provide us with many hooks.

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