Top React Hooks — Lifecycle Hooks

Image for post
Image for post
Photo by T L 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.

useMountedState

The useMountedState hook lets us check a component’s mount state.

It returns a function that returns true is it’s mounted and false if it’s not.

For instance, we can write:

We can just use the returned value to check if the component is mounted.

useUnmountPromise

The useUnmountPromise hook lets us check the mounted state with a promise.

The promise doesn’t resolve if the component unmounts.

For instance, we can write:

We pass in a promise to the mounted function that runs when the component is mounted.

It also takes an error callback than runs when the component is unmounted.

usePromise

The usePromise hook returns a helper function that wraps promises.

Promises in the function only resolves when the component is mounted.

For instance, we can write:

We call the usePromise hook to return the mounted function.

The mounted function takes a promise and returns a promise that resolves to the value of the promise we passed to it.

Then we can use the resolved value however we like.

useLogger

The useLogger lets us logs component transitions.

To use it, we can write:

We have the Counter prop that has the useLogger hook.

It takes the props from the component and logs it.

Then when we pass values to the count prop, they’ll all be logged.

useMount

The useMount hook lets us call a function after the component is mounted.

To use it, we can write:

to use it.

We just pass in a callback that runs when the component is mounted.

Conclusion

The react-use library provides us with lifecycle hooks for running code on mount, unmount, and log the values.

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