useLongPress
특정 버튼을 길게 눌렀을 때에 동작을 제어하는 커스텀 훅.Next.jsReactTypescript
예시
이벤트 로그
API
useLongPress()- Parameters
- onLongPress (Function)롱프레스 시 실행할 콜백 함수
- onClick (Function)일반 클릭 시 실행할 콜백 함수 (선택적)
- delay (Number)롱프레스로 인식할 시간(ms) (기본값: 300)
- Returns
- handlers (Object)마우스/터치 이벤트 핸들러 객체
- isLongPressing (Boolean)현재 롱프레스 상태
개발 및 사용환경
Next.jsReactTypescript사용법
1function UseLongPressExample() {
2 const { handlers, isLongPressing } = useLongPress({
3 onLongPress: () => console.log("롱프레스!"),
4 onClick: () => console.log("클릭!"),
5 delay: 500,
6 });
7
8 return (
9 <button {...handlers}>
10 {isLongPressing ? "롱프레스 중..." : "버튼"}
11 </button>
12 );
13}
Hook
1import { useCallback, useRef, useState } from "react";
2
3interface IProps {
4 onLongPress: () => void;
5 onClick?: () => void;
6 delay?: number;
7}
8
9interface IReturn {
10 handlers: {
11 onMouseDown: () => void;
12 onMouseUp: () => void;
13 onTouchStart: () => void;
14 onTouchEnd: () => void;
15 };
16 isLongPressing: boolean;
17}
18
19const useLongPress = ({
20 onLongPress,
21 onClick,
22 delay = 300,
23}: IProps): IReturn => {
24 const [isLongPressing, setIsLongPressing] = useState(false);
25 const timerRef = useRef<NodeJS.Timeout | null>(null);
26
27 const startPress = useCallback(() => {
28 setIsLongPressing(false);
29 timerRef.current = setTimeout(() => {
30 setIsLongPressing(true);
31 onLongPress();
32 }, delay);
33 }, [onLongPress, delay]);
34
35 const endPress = useCallback(() => {
36 if (timerRef.current) {
37 clearTimeout(timerRef.current);
38 timerRef.current = null;
39 }
40
41 if (!isLongPressing && onClick) {
42 onClick();
43 }
44
45 setIsLongPressing(false);
46 }, [isLongPressing, onClick]);
47
48 return {
49 handlers: {
50 onMouseDown: startPress,
51 onMouseUp: endPress,
52 onTouchStart: startPress,
53 onTouchEnd: endPress,
54 },
55 isLongPressing,
56 };
57};
58
59export default useLongPress;