Last active
March 28, 2023 01:53
-
-
Save wangpin34/f2e77b5159fea095b80fac6b4c5c24e2 to your computer and use it in GitHub Desktop.
React.useEffect variants
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
import { useEffect } from "react" | |
function useDebounceEffect(effect: () => void, deps: unknown[], delay: number) { | |
useEffect(() => { | |
const timeout = setTimeout(() => { | |
effect() | |
}, delay) | |
return () => { | |
clearTimeout(timeout) | |
} | |
}, [...(deps || []), delay]) | |
} |
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
import { useEffect, useRef } from "react" | |
function useThrottleEffect(effect: () => void, deps: unknown[], delay: number) { | |
const lastTime = useRef<number>(Date.now()) | |
useEffect(() => { | |
const now = Date.now() | |
if (now - lastTime.current >= delay) { | |
effect() | |
lastTime.current = now | |
} | |
}, [...(deps || []), effect, delay]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment