← Volver al inicio

useDebounce

Hook personalizado para debounce de valores. Se instala en hooks/enlolab/.

Componente NPM: react

registry/hooks/use-debounce/use-debounce.ts

import { useState, useEffect } from "react"

/**
 * Hook personalizado para debounce de valores
 * 
 * @param value - El valor a debounce
 * @param delay - El delay en milisegundos (default: 500ms)
 * @returns El valor debounced
 * 
 * @example
 * ```tsx
 * const [searchTerm, setSearchTerm] = useState('')
 * const debouncedSearch = useDebounce(searchTerm, 500)
 * 
 * useEffect(() => {
 *   // Hacer búsqueda con debouncedSearch
 * }, [debouncedSearch])
 * ```
 */
export function useDebounce<T>(value: T, delay: number = 500): T {
  const [debouncedValue, setDebouncedValue] = useState<T>(value)

  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedValue(value)
    }, delay)

    return () => {
      clearTimeout(handler)
    }
  }, [value, delay])

  return debouncedValue
}

Instalación

Para instalar este componente, primero configura el registry en tu components.json:

{
  "registries": {
    "@enlolab": {
      "url": "https://ui.enlolab.com/r/{name}.json",
      "headers": {
        "Authorization": "Bearer ${REGISTRY_TOKEN}"
      }
    }
  }
}

Luego instala el componente:

npx shadcn@latest add @enlolab/use-debounce