ยท 2 min read
React-three-fiber First Steps

Jumping a few steps ahead in the Three JS Journey course, I decided to take a look at react-three-fiber the amazing library by the great folks of the Open Collective.
In addition to providing the components and hooks, react-three-fiber also has intelligent defaults for various three.js objects.
The code below is perhaps the simplest example showing how to setup a react App compoenenets that rendes inside document.body. The App compoenents has a Canvas, and the Canvas is the container for the Experience componenent.
The Experience componenent is another simple โgroupโ of a couple of lights, and three objects.
Amazing to see how just 35-40 lines of code can create such a beautiful scene.
The beauty of 3D scenes is in the ability to interact with them and look at things from different angles. This can be enabled by adding a simple OrbitControls component to the Canvas. It seems the developers of the library have chosen to not have the OrbitControls as a default component. So adding it requires some knowledge of how to use the extend function of the library, and the useThree hook. But all in all, just three more lines and you can rotate, zoom, and pan the scene.
Letโs put a spin on things to make them move lively. We can do that by adding a simple animation loop to the Experience component. The animation loop is a function that is called every frame. In this case, we are rotating the cube and the sphere by a small amount every frame. The useFrame hook provides the delta time since the last frame, we just need to add that to the rotation angle to set things into motion!