React + Threejs Mounting

When creating a project with React and Threejs, what would be the advantages and disadvantages of mounting within a React component using useRef() as opposed to appending to body? I’ve tried both methods and so far I’ve found that appending to body has been a much cleaner experience. I then attach events to the body element that facilitates communication between Threejs and React.

To clarify a bit, I currently directly append a Threejs class I created to body from within index.js which is then bundled using webpack.

I’m curious to know what they advantages and drawbacks are between the two solutions.

in react directly mutating children is considered a bad practice, you should never access the dom directly like that.

otherwise, it would make sense in react to use this: GitHub - pmndrs/react-three-fiber: 🇨🇭 A React renderer for Three.js

Thanks for responding to my question.

Do you mean adding an event listener to body from within React and/or appending renderer.domElement to body and/or mounting threejs within a React component using useRef?

I’ve seen react-three-fibers before, I haven’t used it yet because I’d prefer to use a class Three JS implementation as opposed to using tags within React. Just personal preference, but if there’s no other way to achieve the full functionality of Three JS while being performant and in line with best practices then I will switch to using react-three-fibers.

you normally would avoid anything that touches or mutates the dom, adding or removing children, adding events, even plain referencing a dom node. you can render a <canvas> and pass that to webglrenderer. you can ofc achive the full functionality of three, but you’ll have a massively hard time integrating it, making it react to state, etc. expressing an imperative system declaratively is the sole purpose of react, that’s why you use <div> instead of document.createElement(‘div’), it is the same thing that r3f does. they’re not bindings or wrappers, they’re renderers.

1 Like

Thanks for the thorough response! I really appreciate it. Yes, that makes sense, I was trying to get around the integration part with the event handlers. I did get it working, but I can imagine that as the project grows, mutating the body tag to add and remove event listeners is going to make things very complex. I’ll dive forward with react-three-fiber.