improve debounce behavior (#104421)

This commit is contained in:
Joe Reuter 2021-07-07 11:41:12 +02:00 committed by GitHub
parent f5c4a05701
commit a72d0192cb
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -30,12 +30,20 @@ export const useDebouncedValue = <T>(
// Save the initial value
const initialValue = useRef(value);
const flushChangesTimeout = useRef<NodeJS.Timeout | undefined>();
const onChangeDebounced = useMemo(() => {
const callback = debounce((val: T) => {
onChange(val);
unflushedChanges.current = false;
// do not reset unflushed flag right away, wait a bit for upstream to pick it up
flushChangesTimeout.current = setTimeout(() => {
unflushedChanges.current = false;
}, 256);
}, 256);
return (val: T) => {
if (flushChangesTimeout.current) {
clearTimeout(flushChangesTimeout.current);
}
unflushedChanges.current = true;
callback(val);
};