import { useEffect, useRef, useCallback } from "react";

export function useAnimationLoop(callback: () => void) {
  const callbackRef = useRef(callback);
  const rafRef = useRef<number>(0);

  callbackRef.current = callback;

  const loop = useCallback(() => {
    callbackRef.current();
    rafRef.current = requestAnimationFrame(loop);
  }, []);

  useEffect(() => {
    rafRef.current = requestAnimationFrame(loop);
    return () => cancelAnimationFrame(rafRef.current);
  }, [loop]);
}
