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 is0
.options.maxWait
: Max wait time, in milliseconds. Default isInfinity
.options.leading
: Run callback on the leading edge. Default isfalse
.options.trailing
: Run callback on the trailing edge. Default istrue
.
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;