Last active
July 15, 2020 03:51
-
-
Save ramisalem/6e86b5893bb478b5d371c5b73f5e8c62 to your computer and use it in GitHub Desktop.
interval-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 { useState, useEffect, useRef } from 'react'; | |
function useInterval(callback, delay , isRunnig) { | |
const savedCallback = useRef(); | |
const [id , setId] = useState(); | |
// Remember the latest callback. | |
useEffect(() => { | |
savedCallback.current = callback; | |
}, [callback]); | |
// Set up the interval. | |
useEffect(() => { | |
function tick() { | |
savedCallback.current(); | |
} | |
if (delay !== null && isRunnig ) { | |
let id = setInterval(tick, delay); | |
setId(id); | |
} else if(id){ | |
clearInterval(id) | |
} | |
return () => clearInterval(id); | |
}, [delay, isRunnig]); | |
return [id] | |
} | |
export default useInterval ; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment