Rehooks
Hooks

useThrottle

Custom hook that throttles a callback function.

useThrottle

Usage

Component.tsx
import { useThrottle } from "~/hooks/useThrottle";
 
function Component() {
  const [searchTerm, setSearchTerm] = useState<string>("");
  const [results, setResults] = useState<string[]>([]);
 
  const searchAPI = async (term: string) => {
    console.log("🔍 Searching for:", term);
    await new Promise((resolve) => setTimeout(resolve, 500));
    return [
      `Result 1 for ${term}`,
      `Result 2 for ${term}`,
      `Result 3 for ${term}`,
    ];
  };
 
  const handleSearch = useThrottle(
    async (term: string) => {
      if (term.trim() === "") {
        setResults([]);
        return;
      }
      const searchResults = await searchAPI(term);
      setResults(searchResults);
    },
    { wait: 1000 },
  );
 
  return (
    <div>
      <div>
        <input
          type="text"
          placeholder="Search..."
          value={searchTerm}
          onChange={(e) => {
            setSearchTerm(e.target.value);
            handleSearch(e.target.value);
          }}
        />
        <div>
          Try typing quickly - the search is throttled to once per second
        </div>
      </div>
 
      <div>
        {results.map((result, index) => (
          <div key={index}>{result}</div>
        ))}
      </div>
    </div>
  );
}

API

useThrottle

function useThrottle<T extends (...args: any[]) => any>(
  fn: T,
  options: ThrottleOptions = {},
): (...args: Parameters<T>) => void;

Custom hook that throttles a callback function.

Parameters

NameTypeDescription
fnTThe callback function to throttle.
optionsThrottleOptionsThe configuration options.
options.waitnumberThe number of milliseconds to throttle invocations to.
options.leadingbooleanSpecify invoking on the leading edge of the timeout.
options.trailingbooleanSpecify invoking on the trailing edge of the timeout.

Returns

NameTypeDescription
callback(...args: Parameters<T>) => voidA throttled version of the provided callback function. The throttled function will only execute at most once per every wait milliseconds. The callback function will be invoked with the same arguments as the original function, except that the last argument will be an object containing the cancel method, which can be called to cancel the execution of the throttled function.

ThrottleOptions

NameTypeDescription
waitnumberThe number of milliseconds to throttle invocations to.
leadingbooleanSpecify invoking on the leading edge of the timeout.
trailingbooleanSpecify invoking on the trailing edge of the timeout.

On this page