src/hooks/useAnimationLoop.ts 490 B raw
1
import { useEffect, useRef, useCallback } from "react";
2
3
export function useAnimationLoop(callback: () => void) {
4
  const callbackRef = useRef(callback);
5
  const rafRef = useRef<number>(0);
6
7
  callbackRef.current = callback;
8
9
  const loop = useCallback(() => {
10
    callbackRef.current();
11
    rafRef.current = requestAnimationFrame(loop);
12
  }, []);
13
14
  useEffect(() => {
15
    rafRef.current = requestAnimationFrame(loop);
16
    return () => cancelAnimationFrame(rafRef.current);
17
  }, [loop]);
18
}