Created
March 2, 2020 20:38
-
-
Save pablomayobre/f39fff234043452c8935448f45d42b55 to your computer and use it in GitHub Desktop.
useAnimationFrame React Hook, for requestAnimationFrame, with Delta Time and no re-rendering. Uses useLayoutEffect so it can be used before the canvas has been rendered to screen,
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 { useState, useRef, useLayoutEffect } from "react"; | |
const useAnimationFrame = (callback) => { | |
const callbackRef = useRef(callback); | |
const frameRef = useRef(); | |
const timerRef = useRef(); | |
useLayoutEffect(() => { | |
callbackRef.current = callback; | |
}, [callback]); | |
useLayoutEffect(() => { | |
const loop = (time) => { | |
frameRef.current = requestAnimationFrame(loop); | |
let dt = 0; | |
if (timerRef.current !== undefined && timerRef.current !== null) | |
dt = time - timerRef.current; | |
const callback = callbackRef.current; | |
callback(dt/1000); | |
timerRef.current = time; | |
}; | |
frameRef.current = requestAnimationFrame(loop); | |
return () => cancelAnimationFrame(frameRef.current); | |
}, []); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment