Skip to content

Instantly share code, notes, and snippets.

@Goldziher
Created October 21, 2021 19:27
Show Gist options
  • Save Goldziher/4bbc9a2a748c8506c7073b88cff3494e to your computer and use it in GitHub Desktop.
Save Goldziher/4bbc9a2a748c8506c7073b88cff3494e to your computer and use it in GitHub Desktop.
React useInterval hook
import { useEffect, useRef } from 'react';
export function useInterval(
callback: (clearInterval: () => void) => any,
delay: number | null,
): () => void {
const idRef = useRef<null | number>(null);
const clearInterval = () => {
if (idRef.current) {
window.clearInterval(idRef.current);
idRef.current = null;
}
};
useEffect(() => {
if (delay) {
idRef.current = window.setInterval(() => {
callback(clearInterval);
}, delay);
}
return () => clearInterval();
}, [delay]);
return clearInterval;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment