Last active
December 23, 2020 17:33
-
-
Save jasonleehodges/aa097b8835448145cc09b6d0c4860ae0 to your computer and use it in GitHub Desktop.
React based debounce hook
This file contains hidden or 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 { MutableRefObject, useMemo, useRef } from 'react'; | |
export const useDebounce = (milliseconds: number) => { | |
const clearable: MutableRefObject<number | undefined> = useRef(); | |
const debounce = useMemo( | |
() => (fn: () => Promise<void>) => { | |
if (clearable.current !== undefined) { | |
clearTimeout(clearable.current); | |
} | |
clearable.current = window.setTimeout(fn, milliseconds); | |
}, | |
[milliseconds], | |
); | |
return debounce; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To use in your component: