@reworkk/react-debounce
v2.0.0
Published
Use debounce in React
Maintainers
Readme
Use debounce in React
Installation
- yarn add @reworkk/react-debounce
- npm install @reworkk/react-debounce
Advantages
- No dependencies
- Written in TypeScript
Examples
Expensive calculation
const [expensiveCalculation] = useDebounceCallback(() => { ... });
// if user clicks twice, the first call will be cancelled
return <button onClick={expensiveCalculation}>Click</button>Search and HTTP requests
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 <input defaultValue={searchText} onChange={({ target }) => setSearchText(target.value)} />Hooks API reference
useDebounceCallback(callback, options)
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 |
useDebounceState(defaultValue, timeMs)
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 |
