Skip to content

Instantly share code, notes, and snippets.

@balmacefa
Created May 15, 2020 02:47
Show Gist options
  • Select an option

  • Save balmacefa/3e899642ae96eeb78e76d015d9587397 to your computer and use it in GitHub Desktop.

Select an option

Save balmacefa/3e899642ae96eeb78e76d015d9587397 to your computer and use it in GitHub Desktop.
React Frame Loop Hook
import {useRef, useEffect} from 'react'
export const useFrameLoop = (callback) => {
const requestID = useRef();
const previousTime = useRef();
const loop = time => {
if (previousTime.current !== undefined) {
const deltaTime = time - previousTime.current;
callback(time, deltaTime);
}
previousTime.current = time;
requestID.current = requestAnimationFrame(loop);
}
useEffect(()=>{
requestID.current = requestAnimationFrame(loop);
return ()=> cancelAnimationFrame(requestID.current);
}, []);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment