Skip to content

Instantly share code, notes, and snippets.

@davemecha
Created January 6, 2022 19:06
Show Gist options
  • Save davemecha/0653fa2c2b83bfe629d443693a0ebcc5 to your computer and use it in GitHub Desktop.
Save davemecha/0653fa2c2b83bfe629d443693a0ebcc5 to your computer and use it in GitHub Desktop.
Hook for a react effect that is debounced.
// inspired by https://github.com/bellawatt/use-debounce-effect
import { DependencyList, useEffect, useRef } from 'react'
export default function useDebounceEffect(cb: () => void, delay: number, values: DependencyList, runOnInit = false) {
const didMountRef = useRef<boolean>(false);
useEffect(() => {
if (!runOnInit && !didMountRef.current) {
didMountRef.current = true;
return;
}
const handler = setTimeout(cb, delay);
return () => clearTimeout(handler)
}, values)
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment