Skip to content

Commit

Permalink
feat: useDebounce add cancel
Browse files Browse the repository at this point in the history
  • Loading branch information
brickspert committed Aug 19, 2019
1 parent 1d5cd10 commit 26cab31
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 4 deletions.
2 changes: 1 addition & 1 deletion docs/useDebounce.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,5 +45,5 @@ const Demo = () => {
## Reference

```ts
useDebounce(fn, ms: number, args: any[]);
const { cancel } = useDebounce(fn, ms: number, args: any[]);
```
17 changes: 15 additions & 2 deletions src/useDebounce.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,27 @@
import { useCallback, useRef } from 'react';
import useUpdateEffect from './useUpdateEffect';


const useDebounce = (fn: () => any, ms: number = 0, args: any[] = []) => {

const timer = useRef<number>();

useUpdateEffect(() => {
const handle = setTimeout(fn.bind(null, args), ms);

timer.current = window.setTimeout(fn.bind(null, args), ms);
return () => {
// if args change then clear timeout
clearTimeout(handle);
window.clearTimeout(timer.current);
};
}, args);

const cancel = useCallback(() => {
if (timer.current) {
window.clearTimeout(timer.current);
}
}, []);

return { cancel };
};

export default useDebounce;
2 changes: 1 addition & 1 deletion src/useUpdateEffect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const useUpdateEffect: typeof useEffect = (effect, deps) => {
if (isInitialMount.current) {
isInitialMount.current = false;
} else {
effect();
return effect();
}
}, deps);
};
Expand Down

0 comments on commit 26cab31

Please sign in to comment.