typescriptintermediate
useLongPress Hook
Detects long press gestures on touch and mouse devices with configurable threshold.
typescriptPress ⌘/Ctrl + Shift + C to copy
import { useRef, useCallback } from 'react';
interface LongPressOptions {
threshold?: number;
onLongPress: () => void;
onClick?: () => void;
}
export function useLongPress({ threshold = 500, onLongPress, onClick }: LongPressOptions) {
const timerRef = useRef<ReturnType<typeof setTimeout>>();
const isLongPress = useRef(false);
const start = useCallback(() => {
isLongPress.current = false;
timerRef.current = setTimeout(() => {
isLongPress.current = true;
onLongPress();
}, threshold);
}, [threshold, onLongPress]);
const stop = useCallback(() => {
clearTimeout(timerRef.current);
if (!isLongPress.current && onClick) onClick();
}, [onClick]);
return {
onMouseDown: start,
onMouseUp: stop,
onMouseLeave: stop,
onTouchStart: start,
onTouchEnd: stop,
};
}Use Cases
- Context menus
- Mobile interactions
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptbeginner
useHover Hook
Tracks whether an element is being hovered using mouse enter/leave events with a ref.
Best for: Tooltip triggers
#hooks#mouse
typescriptbeginner
useClipboard Hook (Advanced)
Clipboard hook with read, write, and auto-reset of the copied state after a timeout.
Best for: Copy-to-clipboard buttons
#hooks#clipboard
typescriptbeginner
useClickAway Hook
Fires a callback when a click is detected outside the referenced element.
Best for: Dropdown close on outside click
#hooks#click-outside
typescriptintermediate
useFetch — Generic Data Fetching Hook
Custom React hook for data fetching with loading, error, and refetch states using the Fetch API.
Best for: API data fetching
#hooks#fetch