Skip to main content

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 is 0.
    • options.maxWait: Max wait time, in milliseconds. Default is Infinity.
    • options.leading: Change debounced value on the leading edge. Default is false.
    • options.trailing: Change debounced value on the trailing edge. Default is true.

Results:

  • debouncedValue: Debounced value.
  • actions: Actions object.
    • actions.flush: Flush funciton. The finalValue will be returned as debouncedValue if 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;