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 Bug In useDebouncedCallback Doesn't Consider Its Dependencies (#420) #426

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
6 changes: 3 additions & 3 deletions src/useDebouncedCallback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,18 +20,18 @@ const defaultOptions: DebounceOptions = {
* If time is not defined, its default value will be 250ms.
*/
const useDebouncedCallback = <TCallback extends GenericFunction>
(fn: TCallback, dependencies?: DependencyList, wait: number = 600, options: DebounceOptions = defaultOptions) => {
(fn: TCallback, dependencies: DependencyList = [], wait: number = 600, options: DebounceOptions = defaultOptions) => {
const debounced = useRef(debounce<TCallback>(fn, wait, options))

useEffect(() => {
debounced.current = debounce(fn, wait, options)
}, [fn, wait, options])
}, [fn, wait, options, ...dependencies])

useWillUnmount(() => {
debounced.current?.cancel()
})

return useCallback(debounced.current, dependencies ?? [])
return useCallback((...args: Parameters<TCallback>) => debounced.current(...args), [...dependencies])
}

export default useDebouncedCallback
33 changes: 33 additions & 0 deletions test/useDebouncedCallback.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,37 @@ describe('useDebouncedCallback', () => {
expect(spy.called).to.be.true
expect(spy.callCount).to.equal(1)
})

it('should use the latest callback', async () => {
const firstSpy = sinon.spy();
const secondSpy = sinon.spy();

const TestComponent = () => {
const [callback, setCallback] = React.useState(() => firstSpy);
const debouncedCallback = useDebouncedCallback(callback, [callback], 250);

React.useEffect(() => {
debouncedCallback();
debouncedCallback();

setTimeout(() => {
setCallback(() => secondSpy);
}, 100);

setTimeout(() => {
debouncedCallback();
debouncedCallback();
}, 200);
}, [debouncedCallback]);

return <div />;
};

render(<TestComponent />);

await promiseDelay(600);

expect(firstSpy.callCount).to.equal(1);
expect(secondSpy.callCount).to.equal(1);
})
})