Skip to main content

useThrottledValue

Throttle a value.

API

function useThrottledValue<T>(
value: T,
options?: number | { wait?: number; leading?: boolean; trailing?: boolean }
): [
throttledValue: T,
actions: {
flush: (finalValue?: T) => void;
cancel: () => void;
}
];

Params:

  • value: A value that will be throttled.
  • options: Throttle wait time or an options object.
    • options.wait: Throttle wait time, in milliseconds. Default is 0.
    • options.leading: Change throttled value on the leading edge. Default is false.
    • options.trailing: Change throttled value on the trailing edge. Default is true.

Results:

  • throttledValue: Throttled value.
  • actions: Actions object.
    • actions.flush: Flush funciton. The finalValue will be returned as throttledValue if it is specified.
    • actions.cancel: Cancel throttle timer.

Example

Enter value:

Throttled value:
import React, { useState } from "react";
import { useThrottledValue } from "@lilib/hooks";

function Example() {
const [value, setValue] = useState("");
const [throttledValue] = useThrottledValue(value, 500);

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

export default Example;