Skip to main content

useDebounce

Use debounced callback.

API

function useDebounce<T extends (...args: any[]) => any>(
callback: T,
options?:
| number
| { wait?: number; maxWait?: number; leading?: boolean; trailing?: boolean }
): [
debouncedCallback: (...args: Parameters<T>) => ReturnType<T> | undefined,
actions: {
flush: () => ReturnType<T> | undefined;
cancel: () => void;
}
];

Params:

  • callback: Original callback function.
  • options: Debounce wait time or an options object.
    • options.wait: Debounce wait time, in milliseconds. Default is 0.
    • options.maxWait: Max wait time, in milliseconds. Default is Infinity.
    • options.leading: Run callback on the leading edge. Default is false.
    • options.trailing: Run callback on the trailing edge. Default is true.

Results:

  • debouncedCallback: Debounced callback.
  • actions: Actions object.
    • actions.flush: Flush funciton. Run callback immediately.
    • actions.cancel: Cancel debounce timer.

Example

Enter value:

Debounced value:
import React, { useState } from "react";
import { useDebounce, useUpdate } from "@lilib/hooks";

function Example() {
const [value, setValue] = useState("");
const [debouncedValue, setDebouncedValue] = useState("");
const [updateDebouncedValue] = useDebounce(setDebouncedValue, { wait: 500 });

useUpdate(() => {
updateDebouncedValue(value);
}, [value]);

return (
<>
<p>
Enter value:{" "}
<input
value={value}
onChange={(event) => {
setValue(event.target.value);
}}
/>
</p>
<div>Debounced value: {debouncedValue}</div>
</>
);
}

export default Example;