Call UseFrame only when element is on view port

Viewed 265

I'm using the react hook "UseFrame" from react-three-fiber. However, this function is being called at every single frame. Is there a way of calling this callback function only if the react element is within the view port? Should I use a different hook?? I don't want this "UseFrame" hook being called at every frame for those react elements which aren't being showed on the screen.

1 Answers

You can wrap the useFrame hook in it's own component, then only render that component when the canvas is inside the viewport, like this:

import { Canvas, useFrame } from "@react-three/fiber";
import { useInView } from "react-intersection-observer";

function DisableRender() {
  useFrame(() => null, 1000);
}

function App() {
  const { ref, inView } = useInView();
  return (
    <div ref={ref} className="canvasContainer">
      <Canvas>{!inView && <DisableRender />}</Canvas>
    </div>
  );
}
Related