react-use/src/useThrottleFn.ts
streamich 0ccdf9531e feat: 🎸 add useThrottleFn hook that throttles function
This hook used to be called useThrottle, but it also was re-implemented.
2019-03-27 22:22:27 +01:00

37 lines
985 B
TypeScript

import {useState, useRef, useEffect} from 'react';
import useUnmount from './useUnmount'
const useThrottleFn = <T>(fn: (...args: any[]) => T, ms: number = 200, args: any[]) => {
const [state, setState] = useState<T>(null as any);
let timeout = useRef<any>(null);
const nextArgs = useRef(null) as any;
const hasNextArgs = useRef(false) as any;
useEffect(() => {
if (!timeout.current) {
setState(fn(...args));
const timeoutCallback = () => {
if (hasNextArgs.current) {
hasNextArgs.current = false;
setState(fn(...nextArgs.current));
timeout.current = setTimeout(timeoutCallback, ms);
} else {
timeout.current = null;
}
};
timeout.current = setTimeout(timeoutCallback, ms);
} else {
nextArgs.current = args;
hasNextArgs.current = true;
}
}, args);
useUnmount(() => {
clearTimeout(timeout.current);
});
return state;
};
export default useThrottleFn;