useDebounce
useDebounce is a React hook that returns a debounced version of the provided callback function. It helps optimize event handling by delaying function execution and grouping multiple calls into one.
With the default options, the last call runs after wait milliseconds without another call. Pending calls are cancelled when the component unmounts or when wait, leading, or trailing changes. Calling .cancel() only cancels a pending callback, not an already-started network request. The example displays the query locally. To search a server, pass your application's search callback as the first argument to useDebounce.
Interface
function useDebounce<F extends (...args: any[]) => unknown>(
callback: F,
wait: number,
options?: DebounceOptions
): F & { cancel: () => void };Parameters
- callbackrequired · F
The function to debounce.
- waitrequired · number
The number of milliseconds to delay the function execution.
- optionsDebounceOptions
Configuration options for debounce behavior.
- options.leadingboolean · false
If
true, the function is called at the start of the sequence. - options.trailingboolean · true
If
true, the function is called at the end of the sequence.
- options.leadingboolean · false
Return Value
- F & { cancel: () => void }
A debounced function that delays invoking the callback. It also includes a
cancelmethod to cancel any pending debounced execution.
Example
import { useState } from 'react';
import { useDebounce } from 'react-simplikit';
export function SearchInput() {
const [query, setQuery] = useState('');
const [submittedQuery, setSubmittedQuery] = useState('');
const debouncedSearch = useDebounce(setSubmittedQuery, 300);
return (
<section>
<label>
Search
<input
value={query}
onChange={event => {
setQuery(event.target.value);
debouncedSearch(event.target.value);
}}
/>
</label>
<output aria-live="polite">{submittedQuery}</output>
<button type="button" onClick={() => debouncedSearch.cancel()}>
Cancel pending update
</button>
</section>
);
}