Skip to content

Instantly share code, notes, and snippets.

@harrisrobin
Created September 20, 2021 18:41
Show Gist options
  • Save harrisrobin/61bb61cc10a9bf3b82f71f24bde571c8 to your computer and use it in GitHub Desktop.
Save harrisrobin/61bb61cc10a9bf3b82f71f24bde571c8 to your computer and use it in GitHub Desktop.
import { useEffect, useRef } from "react"
import { noop } from "../../utils"
export function useInterval(
callback: () => void,
delay: number | null | false,
immediate?: boolean,
) {
const savedCallback = useRef(noop)
// Remember the latest callback.
useEffect(() => {
savedCallback.current = callback
})
// Execute callback if immediate is set.
useEffect(() => {
if (!immediate) return
if (delay === null || delay === false) return
savedCallback.current()
}, [immediate, delay])
// Set up the interval.
useEffect(() => {
if (delay === null || delay === false) return undefined
const tick = () => 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