2.0.0 • Published 3 years ago

@reworkk/react-debounce v2.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
3 years ago

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

ArgumentDescription
callbackFunction, that will be executed after delay, if DebouncedCallback will be executed
optionsConfiguration object to control hook behavior (Options)

Options

OptionDescription
timeMsDelay before function will be executed (default - 300 ms)
depsDependencies that indicate that hook callback is changed (default - [])

Returns DebouncedCallback, CancelFunction

TypeDescription
DebouncedCallbackFunction that will execute provided callback after timeout (default - 300 ms)
CancelFunctionFunction that allows to prevent callback execution

useDebounceState(defaultValue, timeMs)

Arguments

ArgumentDescription
defaultValueInitial state
timeMsDelay before state will be updated (default - 300 ms)

Returns State, SetStateFunction, CancelFunction

TypeDescription
StateCurrent state
SetStateFunctionFunction that allows to update current state
CancelFunctionFunction that allows to prevent execution of SetStateFunction