Created
June 6, 2019 15:16
-
-
Save qborreda/ecddece84d8f83842e2d96c528ccc80b to your computer and use it in GitHub Desktop.
useInterval custom 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
/** | |
* React custom hook to fire a function given an interval | |
* @usage: useInterval(()=>{...},1000); | |
**/ | |
function useInterval(callback, delay) { | |
const savedCallback = useRef(); | |
useEffect(() => { | |
savedCallback.current = callback; | |
}); | |
useEffect( | |
() => { | |
function tick() { | |
savedCallback.current(); | |
} | |
let id = setInterval(tick, delay); | |
return () => clearInterval(id); | |
}, | |
[delay] | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment