Created
March 7, 2024 18:35
-
-
Save deviationist/2ff2d77dc2f3efca4edf121be3ad47c5 to your computer and use it in GitHub Desktop.
A simple debouce use-hook for React and TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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