useDebouncedValue
Debounce a value.
API
function useDebouncedValue<T>(
value: T,
options?:
| number
| { wait: number; maxWait?: number; leading?: boolean; trailing?: boolean }
): [
debouncedValue: T,
actions: {
flush: (finalValue?: T) => void;
cancel: () => void;
}
];
Params:
value: A value that will be changed.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: Change debounced value on the leading edge. Default isfalse.options.trailing: Change debounced value on the trailing edge. Default istrue.
Results:
debouncedValue: Debounced value.actions: Actions object.actions.flush: Flush funciton. ThefinalValuewill be returned asdebouncedValueif it is specified.actions.cancel: Cancel debounce timer.
Example
Enter value:
Debounced value:
import React, { useState } from "react";
import { useDebouncedValue } from "@lilib/hooks";
function Example() {
const [value, setValue] = useState("");
const [debouncedValue] = useDebouncedValue(value, 500);
return (
<>
<p>
Enter value:{" "}
<input
value={value}
onChange={(event) => {
setValue(event.target.value);
}}
/>
</p>
<div>Debounced value: {debouncedValue}</div>
</>
);
}
export default Example;