Created
January 6, 2022 19:06
-
-
Save davemecha/0653fa2c2b83bfe629d443693a0ebcc5 to your computer and use it in GitHub Desktop.
Hook for a react effect that is debounced.
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
// 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