Skip to content

Instantly share code, notes, and snippets.

@EduVencovsky
Created July 13, 2019 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EduVencovsky/05a59f54be5bec3234d2b369c7c3fffd to your computer and use it in GitHub Desktop.
Save EduVencovsky/05a59f54be5bec3234d2b369c7c3fffd to your computer and use it in GitHub Desktop.
React hook for setTimeout
import { useEffect, useRef, useState } from 'react'
// The callback should setState so it will re trigger the timeout
function useTimeout(callback, delay) {
const savedCallback = useRef()
const [callBackCleanUp, setCallBackCleanUp] = useState(null)
// Remember the latest callback.
useEffect(() => {
savedCallback.current = callback
}, [callback])
// Set up the timeout.
useEffect(() => {
function tick() {
let cleanUp = savedCallback.current()
setCallBackCleanUp(cleanUp)
}
if (delay !== null) {
let id = setTimeout(tick, delay)
return () => {
if (typeof callBackCleanUp === 'function') callBackCleanUp()
clearInterval(id)
}
}
})
}
export default useTimeout
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment