blob: ce7f8f6b580a6b5c34a3f69f595bea810222be1c (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
import React from "react";
/**
* React hook to request animation frame
*
* Taken from https://css-tricks.com/using-requestanimationframe-with-react-hooks/
*/
export const useAnimationFrame = (
callback: (deltaTime: number) => void,
dependencies: any[] = []
) => {
// Use useRef for mutable variables that we want to persist
// without triggering a re-render on their change
const requestRef = React.useRef(0);
const previousTimeRef = React.useRef(0);
const animate = (time: number) => {
if (previousTimeRef.current != undefined) {
const deltaTime = time - previousTimeRef.current;
callback(deltaTime);
}
previousTimeRef.current = time;
requestRef.current = requestAnimationFrame(animate);
};
React.useEffect(() => {
requestRef.current = requestAnimationFrame(animate);
return () => cancelAnimationFrame(requestRef.current);
}, dependencies);
};
|