useDebouncedCallback
useDebouncedCallback 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. Note that if both 'leading' and 'trailing' are set, the function will be called at both the start and end of the delay period. However, it must be called at least twice within debounceMs interval for this to happen, since one debounced function call cannot trigger the function twice.
Interface
function useDebouncedCallback<T>(options: Object): (nextValue: T) => void;Parameters
- optionsrequired · Object
The options object.
- options.onChangerequired · (newValue: T) => void
The callback to debounce. A call with the same value as the last forwarded one is skipped.
- options.timeThresholdrequired · number
The number of milliseconds to delay the function execution.
- 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.onChangerequired · (newValue: T) => void
Return Value
- (nextValue: T) => void
debounced function that forwards the value to
onChange.
Example
import { useDebouncedCallback } from 'react-simplikit';
import { useState } from 'react';
function SearchInput() {
const [query, setQuery] = useState('');
const setQueryDebounced = useDebouncedCallback({
onChange: setQuery,
timeThreshold: 300,
});
return (
<>
<input onChange={e => setQueryDebounced(e.target.value)} />
<p>Searching for: {query}</p>
</>
);
}