Created
March 12, 2021 08:56
-
-
Save Krisztiaan/89c5fc92932f5e6250f3fc76b937edce to your computer and use it in GitHub Desktop.
Simple debounce hook
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
{ | |
"name": "use-debounce", | |
"version": "1.0.0", | |
"main": "useDebounce.ts" | |
} |
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 type { DependencyList } from "react"; | |
import { useEffect, useRef } from "react"; | |
export default function useDebounce( | |
fn: () => void, | |
ms = 0, | |
deps: DependencyList = [] | |
): void { | |
const timeout = useRef<ReturnType<typeof setTimeout>>(); | |
const callback = useRef(fn); | |
// doesn't need to useCallback, not ref checked | |
function reset() { | |
clearTimeout(timeout.current); | |
timeout.current = setTimeout(() => { | |
callback.current(); | |
}, ms); | |
} | |
useEffect(() => { | |
callback.current = fn; | |
}, [fn]); | |
useEffect(() => { | |
reset(); | |
return () => clearTimeout(timeout.current); | |
}, [ms]); | |
useEffect(reset, deps); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment