Skip to content

Instantly share code, notes, and snippets.

@ahtcx
Created November 1, 2019 14:32
Show Gist options
  • Save ahtcx/884e41b5212a4da009edcc1aab9913a0 to your computer and use it in GitHub Desktop.
Save ahtcx/884e41b5212a4da009edcc1aab9913a0 to your computer and use it in GitHub Desktop.
TypeScript version of Dan Abramov's `useInterval`
import { useEffect, useRef } from 'react'
type Callback = () => void
export const useInterval = (callback: Callback, delay: number | null = null) => {
const savedCallback = useRef<Callback>()
useEffect(() => {
savedCallback.current = callback
}, [callback])
useEffect(() => {
const tick = () => savedCallback.current?.()
if (delay !== null) {
const id = window.setInterval(tick, delay)
return () => window.clearInterval(id)
}
}, [delay])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment