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]; };