Skip to main content

useDebouncedCallback

Debounces a callback function. The callback will only execute after the specified delay has passed since the last invocation. Also exposes a progress and isInProgress state for building progress indicators (e.g. search loading bars).

Import

import { useDebouncedCallback } from '@andrejground/lab';

Usage

import React from 'react';
import { useDebouncedCallback } from '@andrejground/lab';

export default function App() {
const [query, setQuery] = React.useState('');

const { callback: debouncedSearch, isInProgress } = useDebouncedCallback(
(value: string) => {
console.log('Searching for:', value);
},
500,
);

return (
<div>
<input
value={query}
onChange={(e) => {
setQuery(e.target.value);
debouncedSearch(e.target.value);
}}
placeholder="Type to search..."
/>
{isInProgress && <span>Searching...</span>}
</div>
);
}

API

const { callback, progress, isInProgress } = useDebouncedCallback(fn, delay);
ParameterTypeDescription
fn(...args) => anyThe callback to debounce
delaynumberDelay in milliseconds

Returns

PropertyTypeDescription
callback(...args) => voidThe debounced version of fn
progressnumber0 or 100 - useful for progress bar animations
isInProgressbooleantrue while waiting for the debounce to fire