I need to make a fetch call when the camera’s position crosses a threshold. I need the function to be callable again, but not until after 1000ms has passed.
Ideally this would happen immediately, but a small delay is tolerable. My main concern is performance as I’m rendering a very complex scene.
This code works, but is it a sensible approach?
import { useMemo, useEffect } from "react";
import { useThree, useFrame } from "@react-three/fiber";
import throttle from "lodash/throttle";
export default function Component() {
const { camera } = useThree();
const throttledFetch = useMemo(
() =>
throttle(
(positionY: number) => {
console.log("fetch with ", positionY);
fetch(`/something?positionY=${positionY}`).then((res) => {
console.log(res);
});
},
1000,
{ leading: true, trailing: false }
),
[]
);
useFrame(() => {
if (camera.position.y < 1.5) {
throttledFetch(camera.position.y);
}
});
useEffect(() => {
return () => {
throttledFetch.cancel();
};
}, [throttledFetch]);
return null;
}