Saltar al contenido
Snippets·Gratis

Hook useDebounce (React)

useDebounce y useDebouncedCallback en TypeScript, más un ejemplo de caja de búsqueda. Los dos cancelan su temporizador cuando el componente se desmonta.

Se instala gratis.

Si tienes PocketCode instalado en tu Android, esto abre la página en la app.

Vista previa

useDebounce hookusedebounce

Hook that returns a value after it stops changing for a delay

import { useEffect, useState } from 'react';

/** Returns value once it has stopped changing for delayMs. */
export function useDebounce<T>(value: T, delayMs = ${1:300}): T {
  const [debounced, setDebounced] = useState(value);

  useEffect(() => {
    const timer = setTimeout(() => setDebounced(value), delayMs);
    // Runs on every change and on unmount, so no timer outlives the component.
    return () => clearTimeout(timer);
  }, [value, delayMs]);

  return debounced;
}
$0

useDebouncedCallback hookusedebouncedcb

Hook that delays a function until calls stop, for onChange or resize handlers

import { useCallback, useEffect, useRef } from 'react';

/** Returns a function that calls callback once calls stop for delayMs. */
export function useDebouncedCallback<A extends unknown[]>(
  callback: (...args: A) => void,
  delayMs = ${1:300},
) {
  const callbackRef = useRef(callback);
  const timerRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);

  // Always call the latest callback without restarting the timer.
  useEffect(() => {
    callbackRef.current = callback;
  }, [callback]);

  // Cancel a pending call when the component unmounts.
  useEffect(() => () => clearTimeout(timerRef.current), []);

  return useCallback(
    (...args: A) => {
      clearTimeout(timerRef.current);
      timerRef.current = setTimeout(() => callbackRef.current(...args), delayMs);
    },
    [delayMs],
  );
}
$0

Debounced search querydebouncesearch

Search state that only reacts once the user stops typing (needs useDebounce)

const [${1:query}, set${2:Query}] = useState('');
const debouncedQuery = useDebounce(${1:query}, ${3:300});

useEffect(() => {
  if (!debouncedQuery) return;
  $0
}, [debouncedQuery]);

Cambios en la 1.0.0

Primera versión.

Relacionados

Snippets de React con TypeScriptGratisSnippets20 snippets de React para archivos .tsx: props con tipos, acciones de useReducer, efectos con limpieza, un hook de contexto con tipos, useLocalStorage, un error boundary y un test con Testing Library. Los imports de React que necesite el archivo los añades tú.runCatching → Result<T, AppError>GratisSnippetsTiny extension that lifts thrown exceptions into a typed Result<T, AppError>, so callers can pattern-match instead of try/catch.Snippets de Kotlin y AndroidGratisSnippets20 snippets de Kotlin para apps Android: estado de UI sellado, un ViewModel de Hilt con StateFlow, corrutinas, entidades y DAO de Room, y estado y listas de Compose. Escribe un prefijo como uistate o hiltvm en un archivo .kt.Snippets de HTML y CSSGratisSnippets8 snippets de HTML (zonas de la página, etiquetas Open Graph, picture, dialog, una tabla con cabeceras) y 12 de CSS (reset, diseños con grid, clamp, variables para el modo oscuro, movimiento reducido, container queries).Snippets de RustGratisSnippets20 snippets de Rust que solo usan la biblioteca estándar, salvo un struct con serde: enums de error con From, cadenas de iteradores, contar con HashMap, let else, hilos con Arc y Mutex, canales y un módulo de tests.Snippets de BashGratisSnippets20 snippets de Bash para scripts: cabecera segura, comprobación de argumentos, getopts, bucles sobre archivos y arrays, limpieza con trap, reintentos y unos cuantos comandos de git. Escribe el prefijo en un archivo .sh.