Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@react-three / react-three-fiber: useLoader() to load new file on props change

I have a functional react component and initial load a gltf model - the path gets passed through the props - this works fine.

But if the props change the component rerenders - I checked that - the path is changed and a new Model should be loaded - but I does not.

How can one achieve this? I want to swap/replace the object that is rendering if the state is updated.

I tried different loaders, set the gltf it self as a state but none of this wokred. I think I miss an underlying concept. Pls Help

  function Character(props) {
      const spinner = useRef();
      console.log(props.model, "from modelpreviewer");
      const gltf = useLoader(GLTFLoader, props.model);
    
      return gltf ? (
        <primitive
          ref={spinner}
          object={gltf.scene}
        />
      ) : null;
    }

The Character Component is rendered like this:

<Canvas
   camera={{ position: [0, 0, 10] }}>
    <ambientLight intensity={0.8} />
    <spotLight intensity={0.7} position={[300, 300, 400]} />
    <Suspense fallback={null}>
      <Character model={props.model} />
    </Suspense>
  </Canvas>
like image 359
Alex Avatar asked Oct 26 '25 07:10

Alex


1 Answers

I test the problem of useLoader when render the texture and it works fine to me. This a simple example which shows the texture will change whenever the props changed.

I guess you're miss the correct path point to props.model. Maybe you can hard code a value of props.model to make sure the file path is correct or not.

Edited

I find the reason why gltf just render once. The answer is here.

You can't reuse meshes or put the same object into the scene twice in webgl/threejs, it will just unmount and remount.

An alternatively solution is to clone the scene.

const { scene } = useLoader(GLTFLoader, url)
const copiedScene = useMemo(() => scene.clone(), [scene])

I also provide a fixed example on codesandbox.

like image 163
bcjohn Avatar answered Oct 28 '25 23:10

bcjohn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!