Skip to content

Commit

Permalink
Fix primefaces#5490: useDebounce fixed
Browse files Browse the repository at this point in the history
  • Loading branch information
melloware committed Jan 9, 2024
1 parent 16be84c commit 5860966
Showing 1 changed file with 22 additions and 7 deletions.
29 changes: 22 additions & 7 deletions components/lib/hooks/useDebounce.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,31 @@
import * as React from 'react';
import { useTimeout } from './useTimeout';
import { useMountEffect, useUnmountEffect } from './Hooks';

export const useDebounce = (initialValue, delay) => {
const [inputValue, setInputValue] = React.useState(initialValue);
const [debouncedValue, setDebouncedValue] = React.useState(initialValue);
const timeout = useTimeout(
() => {
const mountedRef = React.useRef(false);
const timeoutRef = React.useRef(null);
const cancelTimer = () => window.clearTimeout(timeoutRef.current);

useMountEffect(() => {
mountedRef.current = true;
});

useUnmountEffect(() => {
cancelTimer();
});

React.useEffect(() => {
if (!mountedRef.current) {
return;
}

cancelTimer();
timeoutRef.current = window.setTimeout(() => {
setDebouncedValue(inputValue);
},
delay,
inputValue !== debouncedValue
);
}, delay);
}, [inputValue, delay]);

return [inputValue, debouncedValue, setInputValue];
};

0 comments on commit 5860966

Please sign in to comment.