Hello,
I am currently working on a large project that will dynamically change. Thousands of boxes will be constantly loaded and unloaded, so memorizing them is important to avoid unnecessary re-calculations.
Here is a memorized example: Instance Mesh Test - CodeSandbox
You can see that it stores the information about the generates axis in a object in index.js, and then passes it so axis.js to create the blocks on the screen:
var testObj = {
otherData: 0,
data: {
axisSize: [100, 100, 100],
axisColor: ["red", "green", "blue"]
}
};
I also memorized the blocks positions, so they will not change unless the testObj.data changes.
When you click on the blue boxes, the axis size should shrink by 1 on every side. However, this doesn’t happen. Logging the value of the axisSize shows it decreasing, but it never triggers the useMemo.
import "./styles.css";
import React, { useMemo } from "react";
import { Canvas } from "@react-three/fiber";
import { OrbitControls, Instance, Instances } from "@react-three/drei";
export default function App(props) {
var { axisSize, axisColor, axisVoxelSize } = props.testObj.data;
console.log(axisSize);
var memorizedCoords = useMemo(() => {
console.log("calculating");
const axisVoxelList = [];
for (let i = 0; i < axisSize.length; i++) {
let min = -(axisSize[i] * 2);
let max = axisSize[i] * 2;
for (let j = min; j <= max; j += 1) {
if (i === 0) {
axisVoxelList.push(
<Instance
position={[j, 0, 0]}
color={axisColor[i]}
key={`AXISLINEVOXEL${[j, 0, 0]}COORD${i}`}
/>
);
} else if (i === 1) {
axisVoxelList.push(
<Instance
position={[0, j, 0]}
color={axisColor[i]}
key={`AXISLINEVOXEL${[0, j, 0]}COORD${i}`}
/>
);
} else if (i === 2) {
axisVoxelList.push(
<Instance
position={[0, 0, j]}
color={axisColor[i]}
key={`AXISLINEVOXEL${[0, 0, j]}COORD${i}`}
onClick={() => {
console.log("clicked");
props.testObj.data.axisSize = props.testObj.data.axisSize.map(
(x) => (x -= 1)
);
console.log("onClick says");
console.log(props.testObj.data.axisSize);
}}
/>
);
}
}
}
return axisVoxelList;
// Make sure the dependcey is every outside varaible used in the function
}, [axisSize, axisColor]);
return (
<Canvas>
<ambientLight />
<OrbitControls position={[10, 10, 10]} />
<Instances limit={memorizedCoords.length}>
<boxGeometry args={axisVoxelSize} />
<meshStandardMaterial />
{memorizedCoords}
</Instances>
</Canvas>
);
}