|
1 | | -import { useEffect, useRef } from "react"; |
| 1 | +import { useCallback, useEffect, useRef } from "react"; |
| 2 | +import { useForceUpdate } from "@better-hooks/lifecycle"; |
2 | 3 |
|
3 | | -import { |
4 | | - DebounceType, |
5 | | - UseDebounceProps, |
6 | | - DebounceFunctionType, |
7 | | - UseDebounceReturnType, |
8 | | -} from "./use-debounce.types"; |
9 | | -import { useForceUpdate } from "hooks/use-force-update"; |
| 4 | +import { DebounceType, UseDebounceProps, DebounceFunctionType, UseDebounceReturnType } from "hooks"; |
10 | 5 |
|
11 | 6 | export const useDebounce = (props?: UseDebounceProps): UseDebounceReturnType => { |
12 | 7 | const { delay = 400 } = props || {}; |
13 | 8 | const shouldRerenderActive = useRef(false); |
14 | 9 | const timer = useRef<DebounceType>(null); |
15 | 10 | const forceUpdate = useForceUpdate(); |
16 | 11 |
|
17 | | - const rerenderActive = () => { |
| 12 | + const rerenderActive = useCallback(() => { |
18 | 13 | if (shouldRerenderActive.current) forceUpdate(); |
19 | | - }; |
| 14 | + }, [forceUpdate]); |
20 | 15 |
|
21 | 16 | const reset = () => { |
22 | 17 | if (timer.current !== null) clearTimeout(timer.current); |
23 | 18 | timer.current = null; |
24 | 19 | }; |
25 | 20 |
|
26 | | - const debounce: DebounceFunctionType = (callback, dynamicDelay) => { |
27 | | - const time = dynamicDelay ?? delay; |
28 | | - reset(); |
29 | | - timer.current = setTimeout(() => { |
30 | | - timer.current = null; |
31 | | - callback(); |
| 21 | + const debounce: DebounceFunctionType = useCallback( |
| 22 | + (callback, dynamicDelay) => { |
| 23 | + const time = dynamicDelay ?? delay; |
| 24 | + reset(); |
| 25 | + timer.current = setTimeout(() => { |
| 26 | + timer.current = null; |
| 27 | + callback(); |
| 28 | + rerenderActive(); |
| 29 | + }, time); |
32 | 30 | rerenderActive(); |
33 | | - }, time); |
34 | | - rerenderActive(); |
35 | | - }; |
| 31 | + }, |
| 32 | + [delay, rerenderActive], |
| 33 | + ); |
36 | 34 |
|
37 | 35 | useEffect(() => { |
38 | 36 | return reset; |
|
0 commit comments