Use debounce in React
npm install @reworkk/react-debounce- Installation
- Advantages
- Examples
- Expensive calculation
- Search and HTTP requests
- API reference
- useDebounceCallback
- useDebounceState
* yarn add @reworkk/react-debounce
* npm install @reworkk/react-debounce
* No dependencies
* Written in TypeScript
tsx
const [expensiveCalculation] = useDebounceCallback(() => { ... });
// if user clicks twice, the first call will be cancelled
return
`$3
`tsx
const [searchText, setSearchText] = useDebounceState('');
const searchParam = useMemo(() => filterValue === '' ? '' : ?search=${searchText}, [searchText]);useEffect(() => {
fetch(
/api/url${searchParam});
}, [searchParam]);// when you stop typing, setSearchText will be called after 300ms (default timeout)
return setSearchText(target.value)} />
`Hooks API reference
$3
#### Arguments
| Argument | Description |
| --- | --- |
|
callback | Function, that will be executed after delay, if DebouncedCallback will be executed |
| options | Configuration object to control hook behavior (Options) |#### Options
| Option | Description |
| --- | --- |
|
timeMs | Delay before function will be executed (default - 300 ms) |
| deps | Dependencies that indicate that hook callback is changed (default - []) |#### Returns [DebouncedCallback, CancelFunction]
| Type | Description |
| --- | --- |
|
DebouncedCallback | Function that will execute provided callback after timeout (default - 300 ms) |
| CancelFunction | Function that allows to prevent callback execution |$3
#### Arguments
| Argument | Description |
| --- | --- |
|
defaultValue | Initial state |
| timeMs | Delay before state will be updated (default - 300 ms) |#### Returns [State, SetStateFunction, CancelFunction]
| Type | Description |
| --- | --- |
|
State | Current state |
| SetStateFunction | Function that allows to update current state |
| CancelFunction | Function that allows to prevent execution of SetStateFunction` |