Skip to content

Instantly share code, notes, and snippets.

@wangpin34
Last active March 28, 2023 01:53
Show Gist options
  • Save wangpin34/f2e77b5159fea095b80fac6b4c5c24e2 to your computer and use it in GitHub Desktop.
Save wangpin34/f2e77b5159fea095b80fac6b4c5c24e2 to your computer and use it in GitHub Desktop.
React.useEffect variants
import { useEffect } from "react"
function useDebounceEffect(effect: () => void, deps: unknown[], delay: number) {
useEffect(() => {
const timeout = setTimeout(() => {
effect()
}, delay)
return () => {
clearTimeout(timeout)
}
}, [...(deps || []), delay])
}
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