silphius/app/react/hooks/use-animation-frame.js
2024-07-30 22:58:03 -05:00

19 lines
507 B
JavaScript

import {useEffect, useRef} from 'react';
export default function useAnimationFrame(callback) {
const handle = useRef();
const last = useRef();
function animate(time) {
if (last.current != undefined) {
callback((time - last.current) / 1000)
}
last.current = time;
handle.current = requestAnimationFrame(animate);
}
useEffect(() => {
handle.current = requestAnimationFrame(animate);
return () => {
cancelAnimationFrame(handle.current);
};
}, [callback]);
}