Skip to content

Instantly share code, notes, and snippets.

@andresgcarmona
Created July 18, 2023 16:54
Show Gist options
  • Save andresgcarmona/155d7b0fcc87e71e1e2a4fe28d851c5d to your computer and use it in GitHub Desktop.
Save andresgcarmona/155d7b0fcc87e71e1e2a4fe28d851c5d to your computer and use it in GitHub Desktop.
Use interval hook
function useInterval(callback, delay) {
const intervalRef = React.useRef(null);
const savedCallback = React.useRef(callback);
React.useEffect(() => {
savedCallback.current = callback;
}, [callback]);
React.useEffect(() => {
const tick = () => savedCallback.current();
if (typeof delay === 'number') {
intervalRef.current = window.setInterval(tick, delay);
return () => window.clearInterval(intervalRef.current);
}
}, [delay]);
return intervalRef;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment