Skip to content

Commit

Permalink
Represent correct return type from useDebounce()
Browse files Browse the repository at this point in the history
The return type now correctly reflects that the second item can be called manually as a debounced setter, which is super useful in certain situations.
  • Loading branch information
appden committed Dec 13, 2022
1 parent 56f9475 commit 2d17d64
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 7 deletions.
4 changes: 2 additions & 2 deletions src/useDebounce.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useCallback, useRef, useState, Dispatch } from 'react';
import useDebouncedCallback, { ControlFunctions } from './useDebouncedCallback';
import useDebouncedCallback, { DebouncedState } from './useDebouncedCallback';

function valueEquality<T>(left: T, right: T): boolean {
return left === right;
Expand All @@ -19,7 +19,7 @@ export default function useDebounce<T>(
value: T,
delay: number,
options?: { maxWait?: number; leading?: boolean; trailing?: boolean; equalityFn?: (left: T, right: T) => boolean }
): [T, ControlFunctions] {
): [T, DebouncedState<(value: T) => void>] {
const eq = (options && options.equalityFn) || valueEquality;

const [state, dispatch] = useStateIgnoreCallback(value);
Expand Down
9 changes: 4 additions & 5 deletions test/useDebounce.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -301,13 +301,13 @@ describe('useDebounce', () => {
});

it('should preserve debounced object between re-renders', () => {
let cachedDebounced = null;
let cachedDebounced: unknown = null;
function Component({ text }) {
const [value, debounced] = useDebounce(text, 1000);
if (cachedDebounced == null) {
cachedDebounced = debounced;
} else {
expect(cachedDebounced).toBe(debounced)
expect(cachedDebounced).toBe(debounced);
}
return <div>{value}</div>;
}
Expand All @@ -327,8 +327,7 @@ describe('useDebounce', () => {
});
// after runAllTimer text should be updated
expect(tree.text()).toBe('Hello world');
})

});

it('should change debounced.isPending to true as soon as the function is called in a sync way', () => {
function Component({ text }) {
Expand Down Expand Up @@ -356,5 +355,5 @@ describe('useDebounce', () => {
});
// after runAllTimer text should be updated
expect(tree.text()).toBe('Hello world');
})
});
});

0 comments on commit 2d17d64

Please # to comment.