Combine React-three-fiber and threeJS code

Hello,

I have a plain ThreeJS code and I would like to be able to combine it with code in React-three-fiber, React-three-Drei, and other React libraries. Is there any way to easily combine all this? Or would it be best if I translate the ThreeJS code to React-three-fiber? Knowing that the code is quite long and I’m not sure how to go about translating everything.

It’s definitely possible. There’s no way to know if it’s a good idea or not without seeing your code, however.

Yes, it’s not ideal, but sadly I don’t think I’m allowed to post my code.
Maybe if someone has links to project examples combining both, it could help?

function Vanilla(props) {
  const [scene] = useState(() => new THREE.Scene())
  useLayoutEffect(() => {
    const geometry = new THREE.BoxGeometry()
    const material = new THREE.MeshBasicMaterial()
    const mesh = new THREE.Mesh(geometry, material)
    scene.add(mesh)
    // ...
    return () => void scene.dispose()
  }, [])
  return <primitive object={scene} {...props} />
}

...
<Vanilla position={[1, 2, 3]} />

<primitive object={...} /> can mount any existing, foreign threejs object into the scene. But watch out for memory, you are now being responsible to clean up after yourself. useLayoutEffect is called before the component renders on screen, good place to handle imperative logic, and it has a clean-up phase (the return).

Generally it is best to do as much as you can declaratively. Try to break out parts and re-use them. You’ll soon figure that you’re reducing the original code and in the long run it will only help maintenance and sanity overall.

1 Like