Top React Hooks — Scroll, Battery, and Pub/Sub

Image for post
Image for post
Photo by Frank Wang 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-scroll-position

The react-use-scroll-position package lets us watch the scroll position within our React component.

To install it, we run:

Then we can use it by writing:

We called the useScrollPosition , the useScrollXPosition , and useScrollYPosition hooks to get the x and y coordinates of the scroll position.

x should be the same as scrollX .

And y should be the same as scrollY .

react-use-trigger

The react-use-trigger package lets us implement the pub-sub pattern within our React app.

To install it, we run:

or:

Then we can use it by writing:

We have the Sender and Subscriber components to send and subscribe to triggers respectively.

Subscriber has the useTriggerEffect hook to listen to triggered events.

The callback runs when the trigger is run.

The 2nd argument is the trigger to watch for.

The Sender calls the function returned by the createTrigger to trigger the trigger.

So when we click the Send button, we’ll see 'triggered' logged.

We can use also watch the trigger with the useEffect hook.

For instance, we can write:

We have our trigger fooTrigger .

And we pass that to the useTrigger hook.

And we can watch the returned value with the useEffect hook.

react-use

The react-use library is a big library with many handy hooks.

To use it, we install it by running:

It comes with many hooks.

We can use the useBattery gook to track the battery state of our device.

For example, we can write:

to display all the information about our battery.

It has data about the level, whether it’s charging or not, has it finished charging, and discharging time.

Image for post
Image for post
Photo by Alexander Popov on Unsplash

Conclusion

react-use-scroll-position is a useful hook to let us watch the scroll position.

react-use-trigger lets us implement the pub-sub pattern with ease.

react-use is a useful library with many hooks, including a battery status hook.

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