Created
August 18, 2020 17:52
-
-
Save VitorLuizC/3e42972f2f174c926a7f22cd229b4709 to your computer and use it in GitHub Desktop.
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 { useCallback, useEffect, useRef } from 'react'; | |
/** | |
* Hook that provides start and stop functions to handle AnimationFrame API. | |
*/ | |
const useAnimationFrame = () => { | |
const handleRef = useRef<null | number>(null); | |
const stop = useCallback(() => { | |
if (!handleRef.current) return; | |
window.cancelAnimationFrame(handleRef.current); | |
handleRef.current = null; | |
}, [handleRef]); | |
const start = useCallback( | |
(callback: () => void) => { | |
const run = () => { | |
callback(); | |
handleRef.current = window.requestAnimationFrame(run); | |
}; | |
handleRef.current = window.requestAnimationFrame(run); | |
}, | |
[handleRef] | |
); | |
useEffect(() => stop, [handleRef]); | |
return { | |
stop, | |
start | |
}; | |
}; | |
export default useAnimationFrame; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment