Skip to content

Instantly share code, notes, and snippets.

@hyber1z0r
Last active August 10, 2020 19:41
Show Gist options
  • Save hyber1z0r/78e636ba95059cf2c86efdd1800897f3 to your computer and use it in GitHub Desktop.
Save hyber1z0r/78e636ba95059cf2c86efdd1800897f3 to your computer and use it in GitHub Desktop.
useInterval hook
import React, { useEffect, useRef } from 'react';
const useInterval = (callback: () => void, delay: number | null) => {
const savedCallback = useRef(callback);
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
useEffect(() => {
function tick() {
savedCallback.current();
}
if (delay !== null) {
const 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