Top React Hooks — Number Animation and Timers

Image for post
Image for post
Photo by Bonneval Sebastien 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.

useSpring

The useSpring hook lets us update a single numeric value over time.

To use it, we’ve to install by rebound library by running:

For instance, we can use it by writing:

We have the target which is a numeric state.

setTarget lets us set the target state.

useSpring lets us jump to the given value with an animation.

This works when we pass in target to the hook.

useTimeout

The useTimeout hook lets us re-render the component after a specified number of milliseconds.

For example, we can use it by writing:

The useTimeout function takes a duration before reloading in milliseconds.

isReady is a function that determines if the component is ready to reload.

If it is, then it returns false .

cancel is a function that lets us cancel the reloading.

useTimeoutFn

The useTimeoutFn ook lets us run a function after a given delay in milliseconds.

It doesn't re-render the component.

Canceling is automatic.

The timeout is reset on delay change.

The reset function will cancel the previous timeout.

Timeout won’t reset on function changes.

For example, we can use it by writing:

We use the useTimeoutFn hook to create our timer to run a function after a given delay.

The delay is given in milliseconds in the 2nd argument.

We also created the cancelButtonClick function that uses the functions returned by useTimeoutFn .

cancel cancels the timer so the callback won’t run.

reset lets us reset the timer to start from the beginning.

isReady is a function that returns whether the callback is ready to run.

It’s ready if the callback hasn’t been called yet.

Conclusion

The react-use library comes with various useful hooks, including hooks that create timers and animate numbers.

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