add maxWait option like lodash.debounce?
naivefun opened this issue · 4 comments
naivefun commented
Right now it is str8 debounce, how about maxWait option?
xnimorz commented
Hello, @naivefun
Good suggestion :)
You are welcome to PR me or I'll add it some later.
xnimorz commented
I made an example with maxWait
option. It looks more complicated https://codesandbox.io/s/jp8932k769
Where the hook is:
function useDebounce(value, delay, options = {}) {
const [debouncedValue, setDebouncedValue] = useState(value);
const { maxWait } = options;
const maxWaitHandler = useRef(null);
useEffect(
() => {
let handler;
if (value !== debouncedValue) {
handler = setTimeout(() => {
setDebouncedValue(value);
clearTimeout(maxWaitHandler.current);
maxWaitHandler.current = null;
}, delay);
if (maxWait && !maxWaitHandler.current) {
maxWaitHandler.current = setTimeout(() => {
maxWaitHandler.current = null;
setDebouncedValue(value);
clearTimeout(handler);
}, maxWait);
}
}
return () => {
clearTimeout(handler);
};
},
[value, delay]
);
useEffect(
() => () => {
clearTimeout(maxWaitHandler.current);
},
[]
);
return debouncedValue;
}
You can use this code right now by copy-paste it, or I'll publish it later with unit tests to the module.
xnimorz commented
I've published the beta version, which is included the maxWait option.
You can use it right now:
yarn add use-debounce@1.0.0-beta
When I add examples and CHANGELOG I'll cut the release
xnimorz commented
Hello again, @naivefun .
I've cut the 1.0.0 release.
Now you can use:
yarn add use-debounce@1.0.0
The example with maxWait
option is here: https://codesandbox.io/s/4wvmp1xlw4