Rehooks

useDebounceCallback

Debounces a callback, executing it only after a specified delay.

useDebounceCallback

Installation

npx rehooks-cli@latest add useDebounceCallback

Usage

Component.tsx
import { useDebounceCallback } from "~/hooks/useDebounceCallback";
import { useState } from "react";
 
function Component() {
  const [inputValue, setInputValue] = useState<string>("");
 
  const debouncedLog = useDebounceCallback((value: string) => {
    console.log("Debounced Input Value:", value);
  }, 500);
 
  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { value } = e.target;
    setInputValue(value);
    debouncedLog(value);
  };
 
  return (
    <div>
      <h2>Debounced Callback Example</h2>
      <input
        type="text"
        value={inputValue}
        onChange={handleChange}
        placeholder="Type something..."
      />
    </div>
  );
}

API

useDebounceCallback

useDebounceCallback.ts
function useDebounceCallback<T extends (...args: any[]) => void>(
  callback: T,
  delay: number,
): (...args: Parameters<T>) => void;

Returns a debounced version of the provided callback function.

Parameters

NameTypeDescription
callbackTThe callback function that depends on external values.
delaynumberThe debounce delay in milliseconds.

Returns

NameTypeDescription
callbackTA debounced version of the provided callback function.

On this page