Skip to content

Instantly share code, notes, and snippets.

@3YH
Last active May 5, 2020 12:12
Show Gist options
  • Save 3YH/6b92540ca32468ebf5fd67a87182cc3a to your computer and use it in GitHub Desktop.
Save 3YH/6b92540ca32468ebf5fd67a87182cc3a to your computer and use it in GitHub Desktop.
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