Skip to content

Instantly share code, notes, and snippets.

@grantglidewell
Created March 5, 2020 23:17
Show Gist options
  • Save grantglidewell/5ee08b79dea05894a817b8a83b920386 to your computer and use it in GitHub Desktop.
Save grantglidewell/5ee08b79dea05894a817b8a83b920386 to your computer and use it in GitHub Desktop.
import { useEffect, useRef } from 'react'
function useTimeout(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) {
const id = setTimeout(tick, delay)
return () => clearTimeout(id)
}
},
[delay]
)
}
export default useTimeout
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment