useThrottleFn
Throttles a function.
APIâ
const throttledFn = useThrottleFn(fn, delay);
Optionsâ
fn: Function (T)
(Required)- The function to be throttled
delay: number
(Required)- Delay in miliseconds
Returnsâ
throttledFn: T (generic)
- The throttled function
clearTimeout: () => void
- The function to clear the throttle timeout (to cancel throttle)
Examplesâ
http://localhost:3000/
âšī¸ Check the console
Throttle 1 second
Debounce 1 second
- JS
- TS
import { useThrottleFn, useDebounceFn } from 'react-power-ups';
export function DemoThrottle() {
const [fetchData, cancel] = useThrottleFn((value) => {
console.info(`Fetch data by keyword "${value}" âŗ`);
}, 1000);
return (
<>
<h3>Throttle 1 second</h3>
<input type="text" onChange={(e) => fetchData(e.target.value)} />
<button onClick={cancel}>Cancel</button>
</>
);
}
export function DemoDebounce() {
const [fetchData, cancel] = useDebounceFn((value) => {
console.info(`Fetch data by keyword "${value}" âŗ`);
}, 1000);
return (
<>
<h3>Debounce 1 second</h3>
<input type="text" onChange={(e) => fetchData(e.target.value)} />
<button onClick={cancel}>Cancel</button>
</>
);
}
import { useThrottleFn, useDebounceFn } from 'react-power-ups';
export function DemoThrottle() {
const [fetchData, cancel] = useThrottleFn((value: string) => {
console.info(`Fetch data by keyword "${value}" âŗ`);
}, 1000);
return (
<>
<h3>Throttle 1 second</h3>
<input type="text" onChange={(e) => fetchData(e.target.value)} />
<button onClick={cancel}>Cancel</button>
</>
);
}
export function DemoDebounce() {
const [fetchData, cancel] = useDebounceFn((value: string) => {
console.info(`Fetch data by keyword "${value}" âŗ`);
}, 1000);
return (
<>
<h3>Debounce 1 second</h3>
<input type="text" onChange={(e) => fetchData(e.target.value)} />
<button onClick={cancel}>Cancel</button>
</>
);
}
Code: https://github.com/afiiif/react-power-ups/blob/main/src/use-throttle-fn.ts