From 03f9b2f8f74c5c781b399d7016b8b0a5b943ba00 Mon Sep 17 00:00:00 2001 From: melloware Date: Fri, 1 Dec 2023 15:36:20 -0500 Subject: [PATCH] Fix #5490: useDebounce fixed --- components/lib/hooks/useDebounce.js | 29 +++++++++++++++++++++-------- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/components/lib/hooks/useDebounce.js b/components/lib/hooks/useDebounce.js index 29ba443edc..5f2958f682 100644 --- a/components/lib/hooks/useDebounce.js +++ b/components/lib/hooks/useDebounce.js @@ -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]; };