Skip to content

Commit

Permalink
fix(useDebouncedCallback): fix behavior in strict mode
Browse files Browse the repository at this point in the history
  • Loading branch information
kyletsang committed Feb 4, 2024
1 parent 242ab0b commit 16a08a8
Showing 1 changed file with 11 additions and 4 deletions.
15 changes: 11 additions & 4 deletions src/useDebouncedCallback.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useCallback, useMemo, useRef } from 'react'
import { useMemo, useRef } from 'react'
import useTimeout from './useTimeout'
import useMounted from './useMounted'
import useEventCallback from './useEventCallback'
import useWillUnmount from './useWillUnmount'

export interface UseDebouncedCallbackOptions {
wait: number
Expand Down Expand Up @@ -55,6 +55,8 @@ function useDebouncedCallback<TCallback extends (...args: any[]) => any>(

const isTimerSetRef = useRef(false)
const lastArgsRef = useRef<unknown[] | null>(null)
// Use any to bypass type issue with setTimeout.
const timerRef = useRef<any>(0)

const handleCallback = useEventCallback(fn)

Expand All @@ -69,6 +71,11 @@ function useDebouncedCallback<TCallback extends (...args: any[]) => any>(

const timeout = useTimeout()

useWillUnmount(() => {
clearTimeout(timerRef.current)
isTimerSetRef.current = false
})

return useMemo(() => {
const hasMaxWait = !!maxWait

Expand Down Expand Up @@ -161,14 +168,14 @@ function useDebouncedCallback<TCallback extends (...args: any[]) => any>(
if (hasMaxWait) {
// Handle invocations in a tight loop.
isTimerSetRef.current = true
setTimeout(timerExpired, wait)
timerRef.current = setTimeout(timerExpired, wait)
return invokeFunc(lastCallTimeRef.current)
}
}

if (!isTimerSetRef.current) {
isTimerSetRef.current = true
setTimeout(timerExpired, wait)
timerRef.current = setTimeout(timerExpired, wait)
}

return returnValueRef.current
Expand Down

0 comments on commit 16a08a8

Please sign in to comment.