Top React Hooks — Update Hooks

Image for post
Image for post
Photo by Reproductive Health Supplies Coalition 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.

useUnmount

The useUnmount hook lets us call a function when the component will unmount.

For instance, we can use it by writing:

The callback we pass into the hook is run when the component is unmounted.

useUpdateEffect

The useUpdateEffect hook lets us run code after the component is mounted.

The signature is the same as the useEffect hook.

For instance, we can write:

We have the setInterval call in the useEffect callback.

It returns a timer so that we can call clearInterval to clear it in the function the callback returns.

The useUpdateEffect hook runs when count updates.

This means that the console log only logs the value when the component state or props updates.

We pass in an array with the values to watch for and run the callback.

useIsomorphicLayoutEffect

The useIsomorphicLayoutEffect hook is a version of the useLayoutEffect hook that doesn’t show warnings when running in a server-side rendered app.

For instance, we can write:

useDeepCompareEffect

The useDeepCompareEffect hook is an alternate version of the useEffect hook that does deep comparisons to determine whether the callback should be run.

For instance, we can write:

We use the useDeepCompareEffect hook to watch for changes in the options state.

It’s an object, so we can use this hook to watch for changes and run the callback if needed instead of using useEffect .

In the callback, we call inc to increase the count state by the option.step value.

useShallowCompareEffect

The useShallowCompareEffect hook will do shallow comparison instead on each dependency instead of checking for reference equality when determining when to run the callback.

For instance, we can write:

We pass in the options array to run the callback we passed into useShallowCompareEffect when it changes.

The rest of the code is the same as the previous example.

Conclusion

The react-use library have hooks that aren’t available in React itself, including varieties of useEffect .

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