2020-12-03 18:29:47 +01:00
|
|
|
// @flow
|
|
|
|
import React from 'react';
|
|
|
|
|
2022-01-24 17:07:09 +01:00
|
|
|
const useEffectOnce = (effect) => {
|
2020-12-03 18:29:47 +01:00
|
|
|
React.useEffect(effect, []);
|
|
|
|
};
|
|
|
|
|
|
|
|
function useUnmount(fn: () => any): void {
|
|
|
|
const fnRef = React.useRef(fn);
|
|
|
|
|
|
|
|
// update the ref each render so if it change the newest callback will be invoked
|
|
|
|
fnRef.current = fn;
|
|
|
|
|
|
|
|
useEffectOnce(() => () => fnRef.current());
|
|
|
|
}
|
|
|
|
|
2022-01-24 17:07:09 +01:00
|
|
|
export default function useThrottle(value: string, ms: number = 200) {
|
2020-12-03 18:29:47 +01:00
|
|
|
const [state, setState] = React.useState(value);
|
|
|
|
const timeout = React.useRef();
|
|
|
|
const nextValue = React.useRef(null);
|
|
|
|
const hasNextValue = React.useRef(0);
|
|
|
|
|
|
|
|
React.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 = undefined;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
timeout.current = setTimeout(timeoutCallback, ms);
|
|
|
|
} else {
|
|
|
|
nextValue.current = value;
|
|
|
|
hasNextValue.current = true;
|
|
|
|
}
|
2022-01-24 17:07:09 +01:00
|
|
|
}, [ms, value]);
|
2020-12-03 18:29:47 +01:00
|
|
|
|
|
|
|
useUnmount(() => {
|
|
|
|
timeout.current && clearTimeout(timeout.current);
|
|
|
|
});
|
|
|
|
|
|
|
|
return state;
|
|
|
|
}
|