Top React Hooks — Network, Long Press, and Scrolling

Image for post
Image for post
Photo by ROBIN WORRALL 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.

The useNetwork hook lets us detect the network type.

To us it, we can write:

We call the useNetwork hook to return the network state.

The returned object has the online , downlink , effectiveType and rtt properties.

online has the online status.

downlink has internet downlink.

effectiveType has the effective network type.

rtt has the round trip delay.

The useOrientation hook lets us track the screen orientation of the user’s device.

To use it, we write:

We use the useOrientation hook to return an object with the orientation data.

Then object has the angle , which is the angle of the screen.

It also has the type property, which is the screen orientation.

The usePageLeave hook lets us run a callback when the mouse leaves the page.

For instance, we can write:

The hook takes a callback that runs when our mouse leaves the page.

The useStartTyping hook lets us detect when we start typing.

It takes a callback that runs when we start typing.

For example, we can write:

The useWindowScroll hook lets us rerender on window scroll.

For example, we can write:

We have the useWindowScroll hook that returns the x and y coordinates of the scrolling.

The useScroll hook lets us watch for the scrolling of an element.

To use it, we can write:

We created a ref and pass that into the element that we want to watch the scrolling for.

We’ve to set the overflow style so that we scroll the element when there’s overflowing content.

Conclusion

The react-use package has hooks to listening to scrolling on the window and elements.

Also, we can watch for key presses.

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