Created
July 18, 2023 16:54
-
-
Save andresgcarmona/155d7b0fcc87e71e1e2a4fe28d851c5d to your computer and use it in GitHub Desktop.
Use interval hook
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
function useInterval(callback, delay) { | |
const intervalRef = React.useRef(null); | |
const savedCallback = React.useRef(callback); | |
React.useEffect(() => { | |
savedCallback.current = callback; | |
}, [callback]); | |
React.useEffect(() => { | |
const tick = () => savedCallback.current(); | |
if (typeof delay === 'number') { | |
intervalRef.current = window.setInterval(tick, delay); | |
return () => window.clearInterval(intervalRef.current); | |
} | |
}, [delay]); | |
return intervalRef; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment