react-use/src/useThrottle.ts
streamich 452e8d9425 feat: 🎸 simplify and improve useThrottle hook
Create a version of the hook that simply throttled a value, hook that
throttles a function will be called useThrottleFn.

BREAKING CHANGE: 🧨 useThrottle is now a completely different hook
2019-03-27 21:10:57 +01:00

37 lines
939 B
TypeScript

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