useDebounceFn
Debounces a function.
APIâ
const debouncedFn = useDebounceFn(fn, delay);
Optionsâ
fn: Function (T)
(Required)- The function to be debounced
delay: number
(Required)- Delay in miliseconds
Returnsâ
debouncedFn: T (generic)
- The debounced function
clearTimeout: () => void
- The function to clear the debounce timeout (to cancel debounce)
Examplesâ
http://localhost:3000/
âšī¸ Check the console
Debounce 1 second
Throttle 1 second
- JS
- TS
import { useDebounceFn, useThrottleFn } from 'react-power-ups';
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>
</>
);
}
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>
</>
);
}
import { useDebounceFn, useThrottleFn } from 'react-power-ups';
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>
</>
);
}
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>
</>
);
}
Code: https://github.com/afiiif/react-power-ups/blob/main/src/use-debounce-fn.ts