useLongPress
Enable precise control of long-press interactions for both touch and mouse events with useLongPress.
Install:
npm i @uidotdev/usehooks
Description:
The useLongPress hook enhances React applications by managing long-press interactions for both mouse and touch events, thereby ensuring a consistent user experience across devices. This hook not only broadens user interactivity but also allows for customization, providing developers the flexibility to adjust the long-press functionality according to their application needs.
Parameters
Name | Type | Description |
---|---|---|
callback | function | This is the function to be executed when a long press event is detected. |
options | object | This is an optional configuration object provided when calling useLongPress . |
options.threshold | number | This is the time (in milliseconds) the user must press and hold to trigger a long press event. Default value is 400 . |
options.onStart | function | This function is called when the user starts pressing. |
options.onFinish | function | This function is called when a long press event finishes successfully (the user releases after the threshold). |
options.onCancel | function | This function is called when a press event is cancelled (the user releases before the threshold). |
Return Values
Name | Type | Description |
---|---|---|
onMouseDown | function | This is the mouse down event handler. |
onMouseUp | function | This is the mouse up event handler. |
onMouseLeave | function | This is the mouse leave event handler. |
onTouchStart | function | This is the touch start event handler. |
onTouchEnd | function | This is the touch end event handler. |
Demo:
Example:
import * as React from "react";
import { useLongPress } from "@uidotdev/usehooks";
import { closeIcon } from "./icons";
export default function App() {
const [isOpen, setIsOpen] = React.useState(false);
const attrs = useLongPress(
() => {
setIsOpen(true);
},
{
onStart: (event) => console.log("Press started"),
onFinish: (event) => console.log("Press Finished"),
onCancel: (event) => console.log("Press cancelled"),
threshold: 500,
}
);
return (
<section>
<h1>useLongPress</h1>
<button {...attrs} className="primary">
Press Me
</button>
{isOpen && (
<dialog>
<button onClick={() => setIsOpen(false)}>{closeIcon}</button>
<h2>Modal</h2>
<p>This is a modal triggered by a long press.</p>
</dialog>
)}
</section>
);
}
More Hooks:
It’s dangerous to go alone! Master React by learning how to build useHooks yourself.
useDebounce
Delay the execution of function or state update with useDebounce.
useLocalStorage
Store, retrieve, and synchronize data from the browser’s localStorage API with useLocalStorage
useWindowSize
Track the dimensions of the browser window with useWindowSize.
usePrevious
Track the previous value of a variable with usePrevious.
useIntersectionObserver
Track and manage the visibility of your DOM elements within the viewport with useIntersectionObserver.
useNetworkState
Monitor and adapt to network conditions seamlessly with useNetworkState.
useMediaQuery
Subscribe and respond to media query changes with useMediaQuery.
useOrientation
Manage and respond to changes in device orientation with useOrientation.
useSessionStorage
Store, retrieve, and synchronize data from the browser’s session storage with useSessionStorage.
usePreferredLanguage
Adapt to user language preferences dynamically with usePreferredLanguage.
useFetch
Fetch data with accurate states, caching, and no stale responses using useFetch.
useContinuousRetry
Automates retries of a callback function until it succeeds with useContinuousRetry
useVisibilityChange
Track document visibility and respond to changes with useVisibilityChange.
There’s no better way to learn useHooks than by building it yourself.
useScript
Load and manage external JavaScript scripts with useScript.
useRenderInfo
Debug renders and improve performance with useRenderInfo.
useRenderCount
Identify unnecessary re-renders and monitor update frequency with useRenderCount.
useRandomInterval
Execute a callback function at a random interval with useRandomInterval.
useIntervalWhen
Create dynamic timers that can be started, paused, or resumed with useIntervalWhen.
useInterval
Schedule periodic actions like data polling or animations with useInterval.
useLockBodyScroll
Temporarily disable scrolling on the document body with useLockBodyScroll.
useCountdown
Create countdown timers using useCountdown.
useIsClient
Determine whether the code is running on the client-side or server-side with useIsClient.
useQueue
Add, remove, and clear element from a queue data structure with useQueue.
useHover
Track whether an element is being hovered over with useHover.
useTimeout
Create delayed actions or timed events using useTimeout.
Please give us your money.
useEventListener
Listen for events on a target element with useEventListener.
useKeyPress
Detect and perform actions on key press events with useKeyPress.
useMap
Synchronize and update state based on the Map data structure with useMap.
useThrottle
Throttle computationally expensive operations with useThrottle.
useSet
Synchronize and update state based on the Set data structure with useSet.
useCopyToClipboard
Copy text to the clipboard using useCopyToClipboard.
useBattery
Track the battery status of a user’s device with useBattery.
useIdle
Detect user inactivity with useIdle.
useToggle
A hook to toggle a boolean value with useToggle.
useHistoryState
Add undo / redo functionality with useHistoryState.
useGeolocation
Access and monitor a user's geolocation (after they give permission) with useGeolocation.
usePageLeave
Track when a user navigates away from a webpage with usePageLeave.
The all new interactive way to master modern React (for fun and profit).
useObjectState
Manage complex state objects with useObjectState.
useLogger
Debug lifecycle events with useLogger.
useDocumentTitle
Dynamically update the title of a webpage with useDocumentTitle.
useIsFirstRender
Differentiate between the first and subsequent renders with useIsFirstRender.
useFavicon
Dynamically update the favicon with useFavicon.
useDefault
Manage state with default values using useDefault.
useWindowScroll
Track and manipulate the scroll position of a web page with useWindowScroll.
useMeasure
Effortlessly measure and track your component’s dimensions with useMeasure.
useClickAway
Detect clicks outside of specific component with useClickAway.
useList
Manage and manipulate lists with useList.
useCounter
Manage a counter value with minimum and maximum limits with useCounter.
useMouse
Track and retrieve the position of the mouse cursor with useMouse.