Top React Hooks — Renders and States

Image for post
Image for post
Photo by Kumpan Electric 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.

useMediatedState

We can use the useMediatedState hook is a hooks that works like useState , but we can run a callback to manipulate the state before returning it.

To use it, we can write:

to use the useMediatedState hook to remove the spaces in the text we typed in before returning the state .

The first argument is the callback to manipulate the state and the 2nd is the initial value.

useFirstMountState

The useFirstMountState hook lets us check if the component is just mounted.

It’ll return true if it’s just mounted and false otherwise.

For instance, we can use it by writing:

It’ll show true if it’s first mounted and false otherwise.

It takes no arguments.

useRendersCount

We can use the useRendersCount hook to track the renders count including the first render.

For instance, we can write:

We have a button that calls the update function returned by useUpdate to update our component.

It’ll cause a re-render so the rendersCount will increase by 1.

useGlobalState

The useGlobalState hook lets us create a global state that we can share between components.

For instance, we can write:

We called the createGlobalState hook with an initial value to return the useGlobalValue hook.

It returns an array with the value and setValue variables.

value has the state value and setValue has the function to set the value .

We use the useGlobalValue hook in all the components.

In Increase , we used it to increase the value .

In Decrease , we used it to decrease the value .

In App , we only used the hook to get the value .

Conclusion

The react-use library has hooks to get and set states in various ways.

We can also use it to get render count and state.

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