Skip to content

Instantly share code, notes, and snippets.

@EduVencovsky
Last active July 13, 2019 14:22
Show Gist options
  • Save EduVencovsky/466eae6c71c7021a86c3bd5afa6bfcc4 to your computer and use it in GitHub Desktop.
Save EduVencovsky/466eae6c71c7021a86c3bd5afa6bfcc4 to your computer and use it in GitHub Desktop.
React Hook for using setInterval
// https://overreacted.io/making-setinterval-declarative-with-react-hooks/
import { useEffect, useRef } from 'react'
function useInterval(callback, delay) {
const savedCallback = useRef()
// Remember the latest callback.
useEffect(() => {
savedCallback.current = callback
}, [callback])
// Set up the interval.
useEffect(() => {
function tick() {
savedCallback.current()
}
if (delay !== null) {
let 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