Install use-debounce
masterInstall the use-debounce package using yarn or npm.
yarn add use-debounce
# or
npm i use-debounce --saverepository·master·Indexed 25 days ago
https://github.com/xnimorz/use-debounceA collection of React hooks for debouncing and throttling values and callback functions. Version 10.1.1 provides hooks including useDebounce for values, useDebouncedCallback for function execution, and useThrottledCallback for limiting execution frequency. Features include advanced options like maxWait, leading, and trailing edges, as well as lifecycle control methods such as cancel(), flush(), and isPending().
Install the use-debounce package using yarn or npm.
yarn add use-debounce
# or
npm i use-debounce --saveThe following options can be passed to useDebounce and useDebouncedCallback via an options object.
| option | default | Description |
| ---------- | - | :--- |
| maxWait | - | Describes the maximum time func is allowed to be delayed before it's invoked |
| leading | - | This param will execute the function once immediately when called. Subsequent calls will be debounced until the timeout expires. |
| trailing | true | This param executes the function after timeout. |
| equalityFn | (prev, next) => prev === next | [useDebounce ONLY] Comparator function which shows if timeout should be started |Both hooks provide methods to control the debounce cycle:
cancel(): Cancels the pending debounce request.flush(): Immediately executes the pending request.isPending(): Returns a boolean indicating if there is a pending debounce request.useDebounce returns these as part of an array: [value, { cancel, isPending, flush }].
useDebouncedCallback returns these as properties on the returned function: debounced.cancel(), debounced.flush(), etc.
The useThrottledCallback hook allows you to limit the execution frequency of a callback function. It ensures the function is called at most once per specified interval.
Available since version 5.2.0. You can import it either directly from the sub-module or from the main package.
All parameters are identical to useDebouncedCallback, except that the maxWait option is not used for throttled callbacks.
Both useDebounce and useDebouncedCallback accept an options object as a third argument to control execution behavior.
maxWait: The maximum time the function is allowed to be delayed before it is invoked.leading: If true, the function executes immediately on the first call, then subsequent calls are debounced.trailing: (Default: true) Controls whether the function is called again after the timeout expires.// Example with maxWait and cancel
const debounced = useDebouncedCallback(
(value) => {
setValue(value);
},
500,
{ maxWait: 2000 }
);
// Example with leading
const [value] = useDebounce(text, 1000, { leading: true });The function returned by useDebouncedCallback is an extended function that provides several control methods to manage pending executions:
cancel(): Cancels any pending function invocations and clears timers.flush(): Immediately invokes any pending function invocations and returns the result of that invocation (or undefined if nothing was pending).isPending(): Returns true if there are currently any pending function invocations scheduled.The useDebouncedCallback hook creates a debounced version of a function that delays its execution until after a specified wait period has elapsed since the last time it was invoked.
Key Behaviors:
wait is omitted, it defaults to using requestAnimationFrame (approx. 16ms) if available in the environment. If wait is explicitly 0, it behaves like setTimeout(..., 0).undefined.cancel(), flush(), and isPending() methods.leading) or end (trailing) of the timeout period.// Avoid costly calculations while the window size is in flux.
const resizeHandler = useDebouncedCallback(calculateLayout, 150);
window.addEventListener('resize', resizeHandler);
// Invoke `sendMail` when clicked, debouncing subsequent calls.
const clickHandler = useDebouncedCallback(sendMail, 300, {
leading: true,
trailing: false,
});
<button onClick={clickHandler}>click me</button>
// Ensure `batchLog` is 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";The useDebouncedCallback hook accepts an options object to fine-tune debouncing behavior.
| Option | Type | Default | Description |
|---|---|---|---|
leading | boolean | false | If true, the function is invoked on the leading edge of the timeout. |
trailing | boolean | true | If true, the function is invoked on the trailing edge of the timeout. |
flushOnExit | boolean | false | If true, the function is invoked when the component unmounts or the page visibility changes to hidden. Note: This has no effect if trailing is false. |
maxWait | number | undefined | The maximum time the function is allowed to be delayed before it's forced to invoke. |
debounceOnServer | boolean | false | If true, debouncing and timers will occur on the server side as well. |
The following types are exported for use with the useDebouncedCallback hook to provide type safety for options and control functions:
CallOptions: Configuration options for invoking the debounced function.ControlFunctions: Functions used to manually control the debounced callback (e.g., canceling or flushing).DebouncedState: Represents the state of the debounced callback.Options: Configuration options for initializing the hook.import type {
CallOptions,
ControlFunctions,
DebouncedState,
Options,
} from 'use-debounce';Use the useDebouncedCallback hook to debounce a function execution. When using with React synthetic events (like onChange), pass the value directly to the debounced function rather than the event object itself.
import { useDebouncedCallback } from 'use-debounce';
function Input({ defaultValue }) {
const [value, setValue] = useState(defaultValue);
// Debounce callback
const debounced = useDebouncedCallback(
// function
(value) => {
setValue(value);
},
// delay in ms
1000
);
// you should use `e => debounced(e.target.value)` as react works with synthetic events
return (
<div>
<input
defaultValue={defaultValue}
onChange={(e) => debounced(e.target.value)}
/>
<p>Debounced value: {value}</p>
</div>
);
}Use the useDebounce hook to debounce a specific value. The hook compares the previous and next value using shallow equality. If you need to compare objects using a custom comparator, use useDebouncedCallback instead.
import React, { useState } from 'react';
import { useDebounce } from 'use-debounce';
export default function Input() {
const [text, setText] = useState('Hello');
const [value] = useDebounce(text, 1000);
return (
<div>
<input
defaultValue={'Hello'}
onChange={(e) => {
setText(e.target.value);
}}
/>
<p>Actual value: {text}</p>
<p>Debounce value: {value}</p>
</div>
);
}useThrottledCallback hook returns a throttled version of a function. This ensures that the callback is executed at most once within a specified time interval.