Top React Hooks — Long Press and Mouse Position

Image for post
Image for post
Photo by Petr Sevcovic 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 useLongPress hook lets us detect long presses of a key.

To use it, we can write:

We have the useLongPress hook that takes a callback to run when the button us long pressed.

defaultOptions has the options for the hook.

isPreventDefault lets us prevent the default action.

delay is the delay before running the callback.

We pass the object that’s returned by the hook to the button.

The longPressEvent object has various event handlers, including onMouseDown , onTouchStart , onMouseUp , onMouseLeave and onTouchEnd .

The useMedia hook lets us detect the given media query in our React component.

To use it, we run:

We use the useMedia hook with the media query we want to watch for in our component.

It returns a boolean that indicates whether the given media query is matched.

The useMediaDevices hook lets us track connected hardware devices.

For instance, we can use it by writing:

The useMediaDevices hook returns an object with the devices property, which has the deviceId , groupId , kind , and label properties.

kind has the hardware type.

The useMotion hook lets us detect motion with the acceleration sensor.

For instance, we can write:

We have the useMotion hook to return the data from the accelerometer.

It includes the acceleration , accelerationIncludingGravity , rotationRate , and interval .

They give us the acceleration and rotation rate of our device.

The useMouse lets us re-render on mouse position changes.

For instance, we can use it by writing:

The useMouse hook takes a ref for the element that we want to watch the mouse position for.

docX and docY has the mouse position in the whole document.

posX and posY has the position in the element.

elX and elY has the mouse position in the element.

elH and elW has the height and width of the element.

Conclusion

react-use has hooks to detect long mouse presses and mouse positions.

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