Skip to content

Instantly share code, notes, and snippets.

@ramisalem
Last active July 15, 2020 03:51
Show Gist options
  • Save ramisalem/6e86b5893bb478b5d371c5b73f5e8c62 to your computer and use it in GitHub Desktop.
Save ramisalem/6e86b5893bb478b5d371c5b73f5e8c62 to your computer and use it in GitHub Desktop.
interval-hook
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