useThrottleFn
Returns a throttled function wrapper.
Returns a throttled function wrapper.
Import
import { useThrottleFn } from '@kamod-ch/hooks'Live demo
Basic demo
Returns a throttled function wrapper.
Throttled count: 0
import { useState } from 'preact/hooks'
import { useThrottleFn } from '@kamod-ch/hooks'
export default function UseThrottleFnDemo() {
const [count, setCount] = useState(0)
const { run, cancel, flush } = useThrottleFn(() => setCount((value) => value + 1), { wait: 500 })
return (
<div>
<p><strong>Throttled count:</strong> {count}</p>
<div class="demo-actions">
<button type="button" onClick={() => { run(); run(); run() }}>Trigger burst</button>
<button type="button" onClick={flush}>Flush</button>
<button type="button" onClick={cancel}>Cancel</button>
</div>
</div>
)
}
API
TypeScript signature
import type { ThrottleOptions } from '../useThrottle/throttleOptions.js';
type noop = (...args: any[]) => any;
declare function useThrottleFn<T extends noop>(fn: T, options?: ThrottleOptions): {
run: import("../utils/debounce.js").DebouncedFunc<(...args: Parameters<T>) => ReturnType<T>>;
cancel: () => void;
flush: () => ReturnType<T>;
};
export default useThrottleFn;
/SSR considerations
This hook is safe to import during SSR. If your effect body touches the DOM, keep that work inside the effect callback.
Browser compatibility
Works in any modern browser supported by Preact.