React Dojo

Buscar

Busca conceptos, ejercicios y quizzes

dom

useLongPress

Detecta pulsaciones largas sobre cualquier elemento. Dispara un callback tras mantener presionado el tiempo configurado y cancela si el usuario suelta antes.


useLongPress.ts
import { useCallback, useRef } from "react"

interface UseLongPressOptions {
  delay?: number
  onStart?: () => void
  onCancel?: () => void
}

export function useLongPress(
  callback: () => void,
  { delay = 500, onStart, onCancel }: UseLongPressOptions = {}
) {
  const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
  const callbackRef = useRef(callback)
  const onStartRef = useRef(onStart)
  const onCancelRef = useRef(onCancel)

  callbackRef.current = callback
  onStartRef.current = onStart
  onCancelRef.current = onCancel

  const start = useCallback(() => {
    onStartRef.current?.()
    timerRef.current = setTimeout(() => {
      callbackRef.current()
      timerRef.current = null
    }, delay)
  }, [delay])

  const cancel = useCallback(() => {
    if (timerRef.current) {
      clearTimeout(timerRef.current)
      timerRef.current = null
      onCancelRef.current?.()
    }
  }, [])

  return {
    onMouseDown: start,
    onMouseUp: cancel,
    onMouseLeave: cancel,
    onTouchStart: start,
    onTouchEnd: cancel,
  }
}
¿Fue útil?
Inicia sesión para dar feedback