Spaces:
Running
Running
File size: 834 Bytes
a51b9a0 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import { DependencyList, useEffect, useRef } from "react"
export function useAnimationFrame(callback: (time: number) => void, deps: DependencyList | undefined = []) {
// Use useRef for mutable variables that we want to persist
// without triggering a re-render on their change
const requestRef = useRef<number>()
const previousTimeRef = useRef<number>()
const animate = (time: number) => {
if (previousTimeRef.current != undefined) {
const deltaTime = time - previousTimeRef.current
callback(deltaTime)
}
previousTimeRef.current = time;
requestRef.current = requestAnimationFrame(animate);
}
useEffect(() => {
requestRef.current = requestAnimationFrame(animate);
return () => cancelAnimationFrame(requestRef.current as any);
}, deps); // Make sure the effect runs only once
} |