You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
22 lines
855 B
22 lines
855 B
import {useCallback, useEffect, useRef} from "react";
|
|
|
|
export function useAnimationFrame(callback: (delta: number, current: number) => void): void {
|
|
// Use useRef for mutable variables that we want to persist
|
|
// without triggering a re-render on their change
|
|
const requestRef = useRef<number>(0);
|
|
const previousTimeRef = useRef(0);
|
|
|
|
const animate = useCallback(function animate(time: number) {
|
|
if (previousTimeRef.current != 0) {
|
|
const deltaTime = time - previousTimeRef.current;
|
|
callback(deltaTime, time)
|
|
}
|
|
previousTimeRef.current = time;
|
|
requestRef.current = requestAnimationFrame(animate);
|
|
}, [callback])
|
|
|
|
useEffect(() => {
|
|
requestRef.current = requestAnimationFrame(animate);
|
|
return () => cancelAnimationFrame(requestRef.current);
|
|
}, [animate]);
|
|
} |