Combine React-three-fiber and threeJS code

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