I'm using react-three-fiber to display data, coming in real-time, in 3D. Each data object is represented as a cube, with varying size, position, and color. Rather than create a new cube mesh for every data object on every update, I'm trying to use an object pool by memoizing a group of meshes and mutating their properties during react-three-fiber's render loop. To do so, I have a memorized component (using the memo hook), which creates a list of cube components (which I also memoize using useMemo). I put a console.log on the main component and on the subcomponent to make sure they were being memoized properly (which I'm not sure is a reliable way to check, if you could correct me on that please), and found that while the main component only prints once, as it should, the subcomponents print endlessly.

Here's how I made the main component:

const Object3DGroup =  memo(({objectCount, objectData, selectionRef}) => {

  console.log("rerender object group")

  const objs = useMemo(()=>{
    let o = [];

    for (let i = 0; i < objectCount; i++) {
      o.push(
        <Object3D
          key={i}
          objData={objectData}
          objIndex={i}
          selectionRef={selectionRef}
        />
      )
    };

    return o;
  }, []);


  return (
    <>
      {objs}
    </>
  )
});

objectCount is a state variable, objectData and selectionRef are useRef variables. The console.log only happens once.

Here's the code for the subcomponent:

function Object3D({ objData, objIndex, objRef = null, selectionRef, visible = true, children, ...props }) {

  console.log("object render")

  const meshRef = useRef(null);
  const groupRef = useRef(null);
  const textRef = useRef(null);

  const material = useMemo(() => new THREE.MeshBasicMaterial({transparent: true}), []);
  const geometry = useMemo(() => new THREE.BoxGeometry(), []);

  let objmsg;
  const rotation = new THREE.Euler();
  const position = new THREE.Vector3();
  let dimensions = [1];
  let alpha = 0.3;
  let color = "rgb(150,150,150)";

  useFrame((state, delta) => {
    // ...
  }, -1);
  
  return (
    <group ref={groupRef}>
      <mesh
        ref={meshRef}
        geometry={geometry}
        material={material}
        {...props}
      >
      </mesh>
      { children }
    </group>
  );
}

The console.log on this component prints all the time, which leads me to believe that these are not being properly memoized.

What am I missing or doing wrong here?

0

There are 0 best solutions below