Skip to content

Instantly share code, notes, and snippets.

@madflanderz
Created November 26, 2019 10:22
Show Gist options
  • Save madflanderz/dd2e380df84e868d47f400b3dde319e7 to your computer and use it in GitHub Desktop.
Save madflanderz/dd2e380df84e868d47f400b3dde319e7 to your computer and use it in GitHub Desktop.
useInterval hook
import { useEffect, useRef } from "react"
function useInterval(callback: () => void, delay: number) {
const savedCallback = useRef<() => void | undefined>()
useEffect(() => {
savedCallback.current = callback
})
useEffect(() => {
function tick() {
savedCallback.current && savedCallback.current()
}
const id = setInterval(tick, delay)
return () => clearInterval(id)
}, [delay])
}
export default useInterval
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment