Last active
August 10, 2020 19:41
-
-
Save hyber1z0r/78e636ba95059cf2c86efdd1800897f3 to your computer and use it in GitHub Desktop.
useInterval 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 React, { useEffect, useRef } from 'react'; | |
const useInterval = (callback: () => void, delay: number | null) => { | |
const savedCallback = useRef(callback); | |
useEffect(() => { | |
savedCallback.current = callback; | |
}, [callback]); | |
useEffect(() => { | |
function tick() { | |
savedCallback.current(); | |
} | |
if (delay !== null) { | |
const 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