Created
September 8, 2022 14:49
-
-
Save felipecsl/afb987f8b6059814cff0a2ca6020e108 to your computer and use it in GitHub Desktop.
Debounced React useEffect with a wait time in milliseconds
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
// https://stackoverflow.com/a/67504622/51500 | |
import { | |
DependencyList, | |
EffectCallback, | |
useCallback, | |
useEffect, | |
useRef, | |
} from "react"; | |
import { debounce } from "lodash"; | |
export function useLazyEffect( | |
effect: EffectCallback, | |
deps: DependencyList = [], | |
wait = 300 | |
) { | |
const cleanUp = useRef<void | (() => void)>(); | |
const effectRef = useRef<EffectCallback>(); | |
effectRef.current = useCallback(effect, deps); | |
const lazyEffect = useCallback( | |
debounce(() => (cleanUp.current = effectRef.current?.()), wait), | |
[] | |
); | |
useEffect(lazyEffect, deps); | |
useEffect(() => { | |
return () => | |
cleanUp.current instanceof Function ? cleanUp.current() : undefined; | |
}, []); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thank you for this, it saved my bacon today with a tricky debounce setup I was working on