Skip to content

Instantly share code, notes, and snippets.

@deviationist
Created March 7, 2024 18:35
Show Gist options
  • Save deviationist/2ff2d77dc2f3efca4edf121be3ad47c5 to your computer and use it in GitHub Desktop.
Save deviationist/2ff2d77dc2f3efca4edf121be3ad47c5 to your computer and use it in GitHub Desktop.
A simple debouce use-hook for React and TypeScript
import { useEffect, useRef } from 'react';
export const useDebounce = (callback: Function, delay: number) => {
const timeoutRef = useRef<null|NodeJS.Timeout>(null);
useEffect(() => {
return () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
};
}, []);
const debouncedCallback = (...args: any) => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
timeoutRef.current = setTimeout(() => {
callback(...args);
}, delay);
};
return debouncedCallback;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment