@guoyunhe/use-throttle-callback
Version:
Throttle callbacks for React
31 lines (30 loc) • 718 B
JavaScript
import { useEffect, useRef } from 'react';
export function useThrottleCallback(
/**
* Callback function
*/
callback,
/**
* Timeout in ms
* @default 500
*/
timeout = 500) {
const timeoutRef = useRef(0);
const resultRef = useRef(null);
const fn = (...args) => {
if (timeoutRef.current === 0) {
resultRef.current = callback(...args);
timeoutRef.current = window.setTimeout(() => {
timeoutRef.current = 0;
}, timeout);
}
return resultRef.current;
};
useEffect(() => {
return () => {
window.clearTimeout(timeoutRef.current);
timeoutRef.current = 0;
};
}, []);
return fn;
}