Skip to content

Instantly share code, notes, and snippets.

@Krisztiaan
Created March 12, 2021 08:56
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 Krisztiaan/89c5fc92932f5e6250f3fc76b937edce to your computer and use it in GitHub Desktop.
Save Krisztiaan/89c5fc92932f5e6250f3fc76b937edce to your computer and use it in GitHub Desktop.
Simple debounce hook
{
"name": "use-debounce",
"version": "1.0.0",
"main": "useDebounce.ts"
}
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