Last active
October 30, 2020 14:46
-
-
Save fostyfost/fc7fc7b699e3fe5fdfaee1f0d8f8b497 to your computer and use it in GitHub Desktop.
useInterval react hook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect, useRef } from 'react'; | |
export const useInterval = (callback: () => void, timeout?: number): void => { | |
const intervalId = useRef<number>(); | |
const savedCallback = useRef<() => void>(); | |
useEffect(() => { | |
savedCallback.current = callback; | |
}, [callback]); | |
useEffect(() => { | |
if (timeout && timeout > 0) { | |
const tick = (): void => { | |
if (savedCallback && typeof savedCallback.current === 'function') { | |
savedCallback.current(); | |
} | |
}; | |
intervalId.current = setInterval(tick, timeout); | |
} | |
return (): void => { | |
if (intervalId.current) { | |
clearInterval(intervalId.current); | |
} | |
}; | |
}, [timeout]); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment