Top React Hooks — Idleness, Geolocation, and Hashes

Image for post
Image for post
GPhoto by Ehimetalor Akhere Unuabona 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 useGeolocation hook lets us get the location data within our React app.

We can use it by writing:

We use the useGeolocation to get various pieces of data.

It includes the accuracy, latitude, longitude, altitude, speed, and loading state.

The useHover and useHoverDirty gooks lets us watch for hovering of an element.

To use the useHover hook, we can write:

We use the useHover hook with the element of our choice.

The element is a function that takes the hovered parameter and returns some elements.

useHover returns an array with the hoverable and hovered variables.

hoverable indicates whether an element is hoverable.

hovered indicates whether the element is hovered on.

useHover uses onMouseEnter and onMouseLeave to watch for hovering.

useHoverDirty accept a React ref.

And it sets its handlers to the onmouseover and onmouseout properties.

To use it, we write:

useHoverDirty takes a ref, which we also pass to the element we want to watch hover on.

It returns the isHovering variable which indicates whether we’re hovering on it or not.

useHash is a hook that tracks the browser location’s hash.

To use it, we can write:

to use it.

We use the useMount hook which changes the hash when the component mounts.

We did that with the setHash function returned by the useHash hook.

hash has the hash value with the pound sign.

When we get the window.location.href , we’ll get the whole URL with the hash.

The useIdle hook let us determine if the page id idle.

To use it, we write:

We use the useIdle hook with the time to idle in milliseconds in the argument.

It returns the isIdle boolean variable to indicate whether the page is idle or not.

Conclusion

The react-use package comes with many useful hooks like geolocation, watching hovering, and watching for idleness.

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