diff --git a/coding_interviews/frontend/react/useInterval.js b/coding_interviews/frontend/react/useInterval.js new file mode 100644 index 0000000..9612736 --- /dev/null +++ b/coding_interviews/frontend/react/useInterval.js @@ -0,0 +1,23 @@ +import { useEffect, useRef } from 'react'; + +function useInterval(callback, delay) { + const callbackRef = useRef(); + + useEffect(() => { + callbackRef.current = callback; + }, [callback]); + + useEffect(() => { + const interval = setInterval(() => { + callbackRef.current(); + }, delay); + + if ([null, undefined].includes(delay)) { + clearInterval(interval); + } + + return () => { + clearInterval(interval); + }; + }, [delay]); +}