Skip to content

Instantly share code, notes, and snippets.

@danakt
Created March 19, 2019 16:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danakt/ab653afa44039908e69d64ea7eac458f to your computer and use it in GitHub Desktop.
Save danakt/ab653afa44039908e69d64ea7eac458f to your computer and use it in GitHub Desktop.
React hook for creating debounced callback
export const useDebouncedCallback = <T extends (...args: any) => void>(
callback: T,
time: number,
deps: React.DependencyList
) => {
const timerRef = React.useRef<number>(-1);
const memoizedCallback = React.useCallback<T>(
((...args: any): void => {
clearTimeout(timerRef.current);
timerRef.current = setTimeout(() => callback(...args), time);
}) as T,
deps
);
return memoizedCallback;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment