Top React Hooks — Lifecycle and State

Image for post
Image for post
Photo by Peter Conlan 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 hookedUp

React hookedUp is a library with many hooks to make our lives easier.

To install it, we run:

or:

Then we can use the useBoolean hook to let us toggle a boolean value.

For instance, we can write:

We use the useBoolean hook with the initial value.

It returns an object with the toggle and the value properties.

toggle lets us toggle the boolean value.

value has the current value.

The returned object also has the setTrue and setFalse methods to set the boolean state to true and false respectively.

The useOnMount hook lets us run code when the component is mounting.

For example, we can write:

Whatever we have in the useOnMount callback is run.

Likewise, we have the useOnUnmount hook to run code when the component unmounts.

For instance, we can write:

And the callback will run when the component unmounts.

The useLifecycleHooks hook lets us add lifecycle hooks as we did with React class components.

For example, we can write:

We passed an object into the useLifecycleHooks hook to run code when we mount or unmount our component.

onMount is run when the component mounts.

onUnmount is run when the component unmounts.

The useCounter hook lets us create a number state and manage it.

We can use it with one argument which sets the initial state:

The useCounter hook takes an argument which is the initial value.

It returns an object with various properties.

increase increases the value by 1.

decrease decreases the value by 1.

value has the value.

Also, we can set the upper and lower limit of the value .

This way, those functions can’s change our value beyond the range.

For example, we can write:

We can also add the loop property so that the value loops when we change the value beyond the range:

Image for post
Image for post
Photo by NordWood Themes on Unsplash

Conclusion

React hookedUp has various hooks to let us manage various kinds of states and provide us with lifecycle 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