Skip to content

Instantly share code, notes, and snippets.

@jasonleehodges
Last active December 23, 2020 17:33
Show Gist options
  • Save jasonleehodges/aa097b8835448145cc09b6d0c4860ae0 to your computer and use it in GitHub Desktop.
Save jasonleehodges/aa097b8835448145cc09b6d0c4860ae0 to your computer and use it in GitHub Desktop.
React based debounce hook
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;
};
@jasonleehodges
Copy link
Author

jasonleehodges commented Dec 22, 2020

To use in your component:

const debounce = useDebounce(400);
debounce(() => callSomeFunction());

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment