Member-only story

Top React Hooks — Long Press and Mouse Position

John Au-Yeung
3 min readOct 9, 2020

--

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:

import React from "react";
import { useLongPress } from "react-use";
export default function App() {
const onLongPress = () => {
console.log("long pressed");
};
const defaultOptions = {
isPreventDefault: true,
delay: 300
};
const longPressEvent = useLongPress(onLongPress, defaultOptions);
return <button {...longPressEvent}>long press me</button>;
}

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.

--

--

No responses yet