use-debounce
- Version 10.0.6
- Published
- 110 kB
- No dependencies
- MIT license
Install
npm i use-debounceyarn add use-debouncepnpm add use-debounceOverview
Debounce hook for react
Index
Functions
function useDebounce
useDebounce: <T>( value: T, delay: number, options?: { maxWait?: number; leading?: boolean; trailing?: boolean; equalityFn?: (left: T, right: T) => boolean; }) => [T, DebouncedState<(value: T) => void>];function useDebouncedCallback
useDebouncedCallback: <T extends (...args: any) => ReturnType<T>>( func: T, wait?: number, options?: Options, forceUpdate?: Dispatch<SetStateAction<object>>) => DebouncedState<T>;Creates a debounced function that delays invoking
funcuntil afterwaitmilliseconds have elapsed since the last time the debounced function was invoked, or until the next browser frame is drawn.The debounced function comes with a
cancelmethod to cancel delayedfuncinvocations and aflushmethod to immediately invoke them.Provide
optionsto indicate whetherfuncshould be invoked on the leading and/or trailing edge of thewaittimeout. Thefuncis invoked with the last arguments provided to the debounced function.Subsequent calls to the debounced function return the result of the last
funcinvocation.**Note:** If
leadingandtrailingoptions aretrue,funcis invoked on the trailing edge of the timeout only if the debounced function is invoked more than once during thewaittimeout.If
waitis0andleadingisfalse,funcinvocation is deferred until the next tick, similar tosetTimeoutwith a timeout of0.If
waitis omitted in an environment withrequestAnimationFrame,funcinvocation will be deferred until the next frame is drawn (typically about 16ms).See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) for details over the differences between
debounceandthrottle.Function
Parameter func
The function to debounce.
Parameter wait
The number of milliseconds to delay; if omitted,
requestAnimationFrameis used (if available, otherwise it will be setTimeout(...,0)).Parameter options
The options object. Controls if
funcshould be invoked on the leading edge of the timeout.Parameter
{boolean} [options.leading=false] The maximum time
funcis allowed to be delayed before it's invoked.Parameter
{number} [options.maxWait] Controls if
funcshould be invoked the trailing edge of the timeout.Parameter
{boolean} [options.trailing=true]
Returns
{Function} Returns the new debounced function.
Example 1
// Avoid costly calculations while the window size is in flux. const resizeHandler = useDebouncedCallback(calculateLayout, 150); window.addEventListener('resize', resizeHandler)
// Invoke
sendMailwhen clicked, debouncing subsequent calls. const clickHandler = useDebouncedCallback(sendMail, 300, { leading: true, trailing: false, }) <button onClick={clickHandler}>click me// Ensure
batchLogis invoked once after 1 second of debounced calls. const debounced = useDebouncedCallback(batchLog, 250, { 'maxWait': 1000 }) const source = new EventSource('/stream') source.addEventListener('message', debounced)// Cancel the trailing debounced invocation. window.addEventListener('popstate', debounced.cancel)
// Check for pending invocations. const status = debounced.isPending() ? "Pending..." : "Ready"
function useThrottledCallback
useThrottledCallback: <T extends (...args: any) => ReturnType<T>>( func: T, wait: number, { leading, trailing }?: CallOptions) => DebouncedState<T>;Creates a throttled function that only invokes
funcat most once per everywaitmilliseconds (or once per browser frame).The throttled function comes with a
cancelmethod to cancel delayedfuncinvocations and aflushmethod to immediately invoke them.Provide
optionsto indicate whetherfuncshould be invoked on the leading and/or trailing edge of thewaittimeout. Thefuncis invoked with the last arguments provided to the throttled function.Subsequent calls to the throttled function return the result of the last
funcinvocation.**Note:** If
leadingandtrailingoptions aretrue,funcis invoked on the trailing edge of the timeout only if the throttled function is invoked more than once during thewaittimeout.If
waitis0andleadingisfalse,funcinvocation is deferred until the next tick, similar tosetTimeoutwith a timeout of0.If
waitis omitted in an environment withrequestAnimationFrame,funcinvocation will be deferred until the next frame is drawn (typically about 16ms).See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) for details over the differences between
throttleanddebounce.Function
Parameter func
The function to throttle.
Parameter wait
The number of milliseconds to throttle invocations to; if omitted,
requestAnimationFrameis used (if available, otherwise it will be setTimeout(...,0)).Parameter options
The options object.
Parameter
{boolean} [options.leading=true] Specify invoking on the leading edge of the timeout.
Parameter
{boolean} [options.trailing=true] Specify invoking on the trailing edge of the timeout.
Returns
{Function} Returns the new throttled function.
Example 1
// Avoid excessively updating the position while scrolling. const scrollHandler = useThrottledCallback(updatePosition, 100) window.addEventListener('scroll', scrollHandler)
// Invoke
renewTokenwhen the click event is fired, but not more than once every 5 minutes. const throttled = useThrottledCallback(renewToken, 300000, { 'trailing': false }) <button onClick={throttled}>click// Cancel the trailing throttled invocation. window.addEventListener('popstate', throttled.cancel);
Interfaces
interface CallOptions
interface CallOptions {}interface ControlFunctions
interface ControlFunctions<ReturnT> {}interface DebouncedState
interface DebouncedState<T extends (...args: any) => ReturnType<T>> extends ControlFunctions<ReturnType<T>> {}Subsequent calls to the debounced function return the result of the last func invocation. Note, that if there are no previous invocations you will get undefined. You should check it in your code properly.
call signature
(...args: Parameters<T>): ReturnType<T> | undefined;interface Options
interface Options extends CallOptions {}property debounceOnServer
debounceOnServer?: boolean;If the setting is set to true, all debouncing and timers will happen on the server side as well
property maxWait
maxWait?: number;The maximum time the given function is allowed to be delayed before it's invoked.
Package Files (4)
Dependencies (0)
No dependencies.
Dev Dependencies (28)
- @size-limit/preset-small-lib
- @testing-library/jest-dom
- @testing-library/react
- @testing-library/user-event
- @types/jest
- @types/node
- @types/react
- @types/react-dom
- @typescript-eslint/eslint-plugin
- @typescript-eslint/parser
- eslint
- eslint-config-prettier
- eslint-config-standard
- eslint-plugin-import
- eslint-plugin-node
- eslint-plugin-prettier
- eslint-plugin-promise
- eslint-plugin-react-hooks
- eslint-plugin-standard
- jest
- jest-environment-jsdom
- microbundle
- prettier
- react
- react-dom
- size-limit
- ts-jest
- typescript
Peer Dependencies (1)
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/use-debounce.
- Markdown[](https://www.jsdocs.io/package/use-debounce)
- HTML<a href="https://www.jsdocs.io/package/use-debounce"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 2943 ms. - Missing or incorrect documentation? Open an issue for this package.
