useThrottle
Use throttled callback.
API
function useThrottle<T extends (...args: any[]) => any>(
callback: T,
options?: number | { wait?: number; leading?: boolean; trailing?: boolean }
): [
throttledCallback: (...args: Parameters<T>) => ReturnType<T> | undefined,
actions: {
flush: () => ReturnType<T> | undefined;
cancel: () => void;
}
];
Params:
callback
: Original callback function.options
: Throttle wait time or an options object.options.wait
: Throttle wait time, in milliseconds. Default is0
.options.leading
: Run callback on the leading edge. Default isfalse
.options.trailing
: Run callback on the trailing edge. Default istrue
.
Results:
throttledCallback
: Throttled callback.actions
: Actions object.actions.flush
: Flush funciton. Run callback immediately.actions.cancel
: Cancel throttle timer.
Example
Enter value:
Throttled value:
import React, { useState } from "react";
import { useThrottle, useUpdate } from "@lilib/hooks";
function Example() {
const [value, setValue] = useState("");
const [throttledValue, setThrottledValue] = useState("");
const [updateThrottledValue] = useThrottle(setThrottledValue, { wait: 500 });
useUpdate(() => {
updateThrottledValue(value);
}, [value]);
return (
<>
<p>
Enter value:{" "}
<input
value={value}
onChange={(event) => {
setValue(event.target.value);
}}
/>
</p>
<div>Throttled value: {throttledValue}</div>
</>
);
}
export default Example;