(effect: VoidFn, delay: number, deps: any[])
| 7 | * but cancels/re-schedules if they change again before the delay. |
| 8 | */ |
| 9 | export function useDebounceEffect(effect: VoidFn, delay: number, deps: any[]) { |
| 10 | const callbackRef = useRef<VoidFn>(effect) |
| 11 | const timeoutRef = useRef<NodeJS.Timeout | null>(null) |
| 12 | |
| 13 | // Keep callbackRef current |
| 14 | useEffect(() => { |
| 15 | callbackRef.current = effect |
| 16 | }, [effect]) |
| 17 | |
| 18 | useEffect(() => { |
| 19 | // Clear any queued call |
| 20 | if (timeoutRef.current) { |
| 21 | clearTimeout(timeoutRef.current) |
| 22 | } |
| 23 | |
| 24 | // Schedule a new call |
| 25 | timeoutRef.current = setTimeout(() => { |
| 26 | // always call the *latest* version of effect |
| 27 | callbackRef.current() |
| 28 | }, delay) |
| 29 | |
| 30 | // Cleanup on unmount or next effect |
| 31 | return () => { |
| 32 | if (timeoutRef.current) { |
| 33 | clearTimeout(timeoutRef.current) |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | // We want to re‐schedule if any item in `deps` changed, |
| 38 | // or if `delay` changed. |
| 39 | |
| 40 | // eslint-disable-next-line react-hooks/exhaustive-deps |
| 41 | }, [delay, ...deps]) |
| 42 | } |
no outgoing calls
no test coverage detected