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 Dec 1, 2023
1 parent 39290fa commit 03f9b2f
Showing 1 changed file with 21 additions and 8 deletions.
29 changes: 21 additions & 8 deletions components/lib/hooks/useDebounce.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,29 @@
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(
() => {
setDebouncedValue(inputValue);
},
delay,
inputValue !== debouncedValue
);
const mountedRef = React.useRef(false);
const timeoutRef = React.useRef(null);
const cancelTimer = () => window.clearTimeout(timeoutRef.current);

React.useEffect(() => {
if (mountedRef.current) {
cancelTimer();
timeoutRef.current = window.setTimeout(() => {
setDebouncedValue(inputValue);
}, delay);
}
}, [inputValue, delay]);

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

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

return [inputValue, debouncedValue, setInputValue];
};

0 comments on commit 03f9b2f

Please sign in to comment.