Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(useDebouncedCallback): fix behavior in strict mode #98

Merged
merged 1 commit into from
Feb 8, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
kyletsang marked this conversation as resolved.
Show resolved Hide resolved

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
Loading