Skip to content
Open
Show file tree
Hide file tree
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
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,30 @@ describe('useDebounceCallback()', () => {
expect(debouncedCallback).not.toHaveBeenCalled()
})

it('should cancel the debounced callback on unmount', () => {
const delay = 500
const debouncedCallback = vitest.fn()
const { result, unmount } = renderHook(() =>
useDebounceCallback(debouncedCallback, delay),
)

act(() => {
result.current('argument')
})

// The callback should not be invoked immediately
expect(debouncedCallback).not.toHaveBeenCalled()

// Unmount the component
unmount()

// Fast forward time past the debounce delay
vitest.advanceTimersByTime(delay + 100)

// The callback should not be invoked after unmount
expect(debouncedCallback).not.toHaveBeenCalled()
})

it('should flush the debounced callback', () => {
const delay = 500
const debouncedCallback = vitest.fn()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect, useMemo, useRef } from 'react'
import { useMemo, useRef } from 'react'

import debounce from 'lodash.debounce'

Expand Down Expand Up @@ -87,6 +87,8 @@ export function useDebounceCallback<T extends (...args: any) => ReturnType<T>>(
const debounced = useMemo(() => {
const debouncedFuncInstance = debounce(func, delay, options)

debouncedFunc.current = debouncedFuncInstance

const wrappedFunc: DebouncedState<T> = (...args: Parameters<T>) => {
return debouncedFuncInstance(...args)
}
Expand All @@ -106,10 +108,5 @@ export function useDebounceCallback<T extends (...args: any) => ReturnType<T>>(
return wrappedFunc
}, [func, delay, options])

// Update the debounced function ref whenever func, wait, or options change
useEffect(() => {
debouncedFunc.current = debounce(func, delay, options)
}, [func, delay, options])

return debounced
}