Skip to content

useDebounceFn

Returns a debounced function with run, cancel, and flush.

Returns a debounced function with run, cancel, and flush.

Import

import { useDebounceFn } from '@kamod-ch/hooks'

Live demo

Basic demo

Returns a debounced function with run, cancel, and flush.

Debounced count: 0

import { useState } from 'preact/hooks'
import { useDebounceFn } from '@kamod-ch/hooks'

export default function UseDebounceFnDemo() {
  const [count, setCount] = useState(0)
  const { run, cancel, flush } = useDebounceFn(() => setCount((value) => value + 1), { wait: 500 })

  return (
    <div>
      <p><strong>Debounced count:</strong> {count}</p>
      <div class="demo-actions">
        <button type="button" onClick={() => { run(); run(); run() }}>Queue burst</button>
        <button type="button" onClick={flush}>Flush</button>
        <button type="button" onClick={cancel}>Cancel</button>
      </div>
    </div>
  )
}

API

TypeScript signature
import type { DebounceOptions } from '../useDebounce/debounceOptions.js';
type noop = (...args: any[]) => any;
declare function useDebounceFn<T extends noop>(fn: T, options?: DebounceOptions): {
    run: import("../utils/debounce.js").DebouncedFunc<(...args: Parameters<T>) => ReturnType<T>>;
    cancel: () => void;
    flush: () => ReturnType<T>;
};
export default useDebounceFn;
/

SSR considerations

This hook is safe to import during SSR. If your effect body touches the DOM, keep that work inside the effect callback.

Browser compatibility

Works in any modern browser supported by Preact.

Related hooks