Skip to main content

useDebouncedCallback

The useDebouncedCallback hook debounces a function instead of a value. The function runs only after the given delay has passed without another call, which is ideal for search-as-you-type, autosave, or resize handlers.

Usage​

Installation​

import { useDebouncedCallback } from "hookstorm";

Parameters​

  • callback — The function to debounce. The latest version is always used, so it never reads stale props or state.
  • delay — (optional) The delay in milliseconds. Default: 500.

Return Values​

  • run — The debounced function. Accepts the same arguments as callback.
  • cancel — Cancels the pending call, if any.
  • flush — Immediately runs the pending call, if any.

Example Usage​

import { ReactElement } from "react";
import { useDebouncedCallback } from "hookstorm";

export default function Search(): ReactElement {
const { run: search, flush } = useDebouncedCallback((query: string) => {
console.log("Searching for", query);
}, 400);

return (
<input
placeholder="Search..."
onChange={(e) => search(e.target.value)}
onBlur={flush}
/>
);
}

Notes​

  • Only the arguments of the last call are used.
  • A pending call is cancelled automatically when the component unmounts.
  • run, cancel and flush keep a stable identity between renders (run changes only when delay changes).