Top React Hooks — Promises, Tweens, and Manual Update

Image for post
Image for post
Photo by Sheri Hooley 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.

useTween

The useTween hook animates a number between 0 and 1.

For instance, we can use it by writing:

We just call the useTween hook to return the number being animated.

We can also set the easing, duration, and delay before the animation starts.

To do that, we write:

The first argument is the easing name.

The names can be one of the ones in this list.

The 2nd is the duration of the animation.

The 3rd is the delay before running the animation.

The numbers are in milliseconds.

useUpdate

The useUpdate hook lets us return a function that forces a re-render when it’s called.

To use it, we can write:

We called the useUpdate hook to return the update function.

Then we passed that into the onClick handler.

useAsync

To run code that returns a promise cleanly, we can use the useAsync hook.

To use it, we write:

We called the useAsync hook with an async function as its callback.

Inside the callback, we return a promise by calling the fetch function and then returning the result from the response.

The 2nd argument of the hook is an array and lets us listen for value changes and reload if the value changes.

The hook returns the state object which has various properties.

loading indicates whether the promise is loading or not.

error indicates whether an error occurs.

value has the value resolved from the promise.

useAsyncFn

The useAsyncFn is similar to the useAsync hook.

The signature is the same as useAsync .

The difference is that it returns a function that lets us invoke the promise again.

For instance, we can write:

We pass in the same promise as we did with useAsync .

It returns the state like useAsync .

In addition, it returns the getData function to let us get the data.

The data is only retrieved if we call it.

Conclusion

The react-use library provides us with hooks to animate numbers, manually update a component, and run promises cleanly.

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