Skip to content

Instantly share code, notes, and snippets.

@VitorLuizC
Created August 18, 2020 17:52
Show Gist options
  • Save VitorLuizC/3e42972f2f174c926a7f22cd229b4709 to your computer and use it in GitHub Desktop.
Save VitorLuizC/3e42972f2f174c926a7f22cd229b4709 to your computer and use it in GitHub Desktop.
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