Skip to content

Instantly share code, notes, and snippets.

@ospfranco
Created July 30, 2020 06:29
Show Gist options
  • Save ospfranco/8a23054197b7817f9e367637819d0f98 to your computer and use it in GitHub Desktop.
Save ospfranco/8a23054197b7817f9e367637819d0f98 to your computer and use it in GitHub Desktop.
ReactJS hook for setting interval
export function useInterval (callback: () => void, delay: number) {
const savedCallback = useRef()
// Remember the latest callback.
useEffect(() => {
savedCallback.current = callback
}, [callback])
// Set up the interval.
useEffect(() => {
function tick () {
if (savedCallback.current) {
savedCallback.current()
}
}
if (delay !== null) {
const id = setInterval(tick, delay)
return () => clearInterval(id)
}
}, [delay])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment