Skip to content

Commit

Permalink
refactor(hooks): added useTimer hook to useDebounce hook and useDoubl…
Browse files Browse the repository at this point in the history
…eClick hook to remove unnecesary repeated code.
  • Loading branch information
caarlosdamian committed Feb 4, 2024
1 parent f61a5a4 commit ba03667
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 30 deletions.
24 changes: 9 additions & 15 deletions src/hooks/useDebounce.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,21 @@
import { useEffect, useRef } from 'react';
import { useEffect } from 'react';
import { useTimer } from './useTimer';

export const useDebounce = <T extends any[]>(
callback: (...args: T) => any,
callback: (...args: T) => void,
delay: number
) => {
const callbackRef = useRef<number | null>(null);
const { setTimer, clearTimer } = useTimer();

useEffect(() => {
return () => {
if (callbackRef.current) {
clearTimeout(callbackRef.current);
}
clearTimer();
};
}, []);
}, [clearTimer]);

const debouncedCallback = (...rest: T) => {
if (callbackRef.current) {
clearTimeout(callbackRef.current);
}

callbackRef.current = setTimeout(() => {
callback(...rest);
}, delay);
const debouncedCallback = (...args: T) => {
clearTimer();
setTimer(() => callback(...args), delay);
};

return debouncedCallback;
Expand Down
21 changes: 6 additions & 15 deletions src/hooks/useDoubleClick.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useCallback, useRef, MouseEvent } from 'react';
import { useCallback, MouseEvent } from 'react';
import { useTimer } from './useTimer';

type ClickCallback = (event: MouseEvent<any>) => any | void;

Expand All @@ -7,27 +8,17 @@ export const useDoubleClick = <T>(
click: ClickCallback,
timeout = 250
) => {
const clickTimeout = useRef<ReturnType<typeof setTimeout> | undefined>(
undefined
);

const clearClickTimeout = () => {
if (clickTimeout.current !== undefined) {
clearTimeout(clickTimeout.current);
clickTimeout.current = undefined;
}
};
const { clearTimer, setTimer } = useTimer();

return useCallback(
(event: MouseEvent<T>) => {
clearClickTimeout();
clearTimer();
if (click && event.detail === 1) {
clickTimeout.current = setTimeout(() => {
click(event);
}, timeout);
setTimer(() => click(event), timeout);
}
if (event.detail % 2 === 0) {
doubleClick(event);
setTimer(() => doubleClick(event), timeout);
}
},
[click, doubleClick, timeout]
Expand Down

0 comments on commit ba03667

Please sign in to comment.