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 is0
.options.leading
: Change throttled value on the leading edge. Default isfalse
.options.trailing
: Change throttled value on the trailing edge. Default istrue
.
Results:
throttledValue
: Throttled value.actions
: Actions object.actions.flush
: Flush funciton. ThefinalValue
will be returned asthrottledValue
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;