Created
December 18, 2021 08:47
-
-
Save 0xLDev/1c5503ca787c4866b7faeede35e0fce4 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 { useCallback, useEffect, useState, useRef } from 'react'; | |
export const useInterval = (callback, delay) => { | |
const callbackRef = useRef(callback); | |
const [intervalHandle, setIntervalHandle] = useState(null); | |
const [trigger, setTrigger] = useState(); | |
useEffect(() => { | |
callbackRef.current = callback; | |
}, [callback]); | |
useEffect(() => { | |
const interval = setInterval(() => { | |
if (callbackRef.current) { | |
callbackRef.current(); | |
} | |
}, delay); | |
setIntervalHandle(interval); | |
return () => { | |
clearInterval(interval); | |
}; | |
}, [delay, trigger]); | |
const isRunning = !!intervalHandle; | |
const stop = useCallback(() => { | |
if (intervalHandle) { | |
clearInterval(intervalHandle); | |
setIntervalHandle(null); | |
} | |
}, [intervalHandle]); | |
const restart = useCallback(() => { | |
setTrigger({}); | |
}, []); | |
return { isRunning, stop, restart }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment