Created
October 21, 2021 19:27
-
-
Save Goldziher/4bbc9a2a748c8506c7073b88cff3494e to your computer and use it in GitHub Desktop.
React useInterval hook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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