Last active
May 5, 2020 12:12
-
-
Save 3YH/6b92540ca32468ebf5fd67a87182cc3a to your computer and use it in GitHub Desktop.
This file contains hidden or 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 { useRef, useEffect } from 'react'; | |
const useInterval = (callback, delay) => { | |
const savedCallback = useRef(); | |
// Remember the latest function. | |
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