Skip to main content

useDebounceFn

Debounces a function.


API​

const debouncedFn = useDebounceFn(fn, delay);

Options​

  • fn: Function (T)(Required)
    • The function to be debounced
  • delay: number(Required)
    • Delay in miliseconds

Returns​

  • debouncedFn: T (generic)
    • The debounced function
  • clearTimeout: () => void
    • The function to clear the debounce timeout (to cancel debounce)

Examples​

http://localhost:3000/
ℹī¸ Check the console

Debounce 1 second

Throttle 1 second

import { useDebounceFn, useThrottleFn } from 'react-power-ups';

export function DemoDebounce() {
const [fetchData, cancel] = useDebounceFn((value: string) => {
console.info(`Fetch data by keyword "${value}" âŗ`);
}, 1000);

return (
<>
<h3>Debounce 1 second</h3>
<input type="text" onChange={(e) => fetchData(e.target.value)} />
<button onClick={cancel}>Cancel</button>
</>
);
}

export function DemoThrottle() {
const [fetchData, cancel] = useThrottleFn((value: string) => {
console.info(`Fetch data by keyword "${value}" âŗ`);
}, 1000);

return (
<>
<h3>Throttle 1 second</h3>
<input type="text" onChange={(e) => fetchData(e.target.value)} />
<button onClick={cancel}>Cancel</button>
</>
);
}

Code: https://github.com/afiiif/react-power-ups/blob/main/src/use-debounce-fn.ts