Skip to content

Instantly share code, notes, and snippets.

@MarekZeman91
Created April 18, 2022 00:01
Show Gist options
  • Save MarekZeman91/2df9eb11716bc6adc807651a62d77739 to your computer and use it in GitHub Desktop.
Save MarekZeman91/2df9eb11716bc6adc807651a62d77739 to your computer and use it in GitHub Desktop.
import { useMemo, useRef } from 'react';
import { useScope } from './useScope';
export type UseDebouncerCallback = (...args: any[]) => void;
export const useDebouncer = <T extends UseDebouncerCallback>(
callback: T,
delay: number,
runFirst?: boolean
): T & { clear: () => void } => {
const scope = useScope({ callback, delay, runFirst });
const timeout = useRef<number>(0);
return useMemo(() => {
const debounce = (...args: T[]) => {
if (!timeout.current && scope.runFirst) {
scope.callback(...args);
}
window.clearTimeout(timeout.current);
timeout.current = window.setTimeout(() => {
timeout.current = 0;
scope.callback(...args);
}, scope.delay);
};
debounce.clear = () => window.clearTimeout(timeout.current);
return debounce as T & { clear: () => void };
}, [scope]);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment