Skip to content

Instantly share code, notes, and snippets.

@pablomayobre
Created March 2, 2020 20:38
Show Gist options
  • Save pablomayobre/f39fff234043452c8935448f45d42b55 to your computer and use it in GitHub Desktop.
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,
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