React Three Fiber
Create beautiful 3D Objects in the web.
What is React Three Fiber?
React-three-fiber is a React renderer that is wrapped around three.js. Three.js allows you to easily interact with WebGL to render 3d models in the browser. With react-three-fiber this becomes even easier!
With just a few lines of code you can create new 3D scenes in React. React three fiber allows you to utilize React design patterns to componentize your 3D scene making it easy to build complex and interactive applications.
Getting Started
To get started with React three fiber, all you need is a React project and npm.
Let’s start by creating a new React app.
npx create-react-app react-tutorial
Once this is completed we need to install the necessary dependencies. The only required dependencies to get started with react-three-fiber are three and react-three-fiber itself. On top of this, it’s probably also a good idea to install the drei library which is a utility library for react-three-fiber. It provides a bunch of prebuilt components and utilities that make it easy to start building.
To install all necessary dependencies we run the following command.
yarn add @react-three/fiber @react-three/drei three
Or if you are working with npm instead of yarn…
npm install @react-three/fiber @react-three/drei three
This will install all the necessary dependencies to your react project and now we’re ready to start building!
This is the basic example provided in the react-three-fiber documentation. The above code generates the following 3D scene.
Everything that you put between your <Canvas> tags will render in 3D. In this case, we have two <Box> components that are given interesting properties.
React-three-fiber provides a hook call useFrame that allows you to hook up to the frame rate of the scene and update objects accordingly. In order to do this we have to use react useRef hook to create a reference to the box instance and update it within the useFrame hook.
Each box also has an active property that is toggled with a click. This combines React state with react-three-fiber to scale the Box and change it’s color depending on whether or not the state is active or not.
That’s it! We’ve created a simple 3d scene using React three fiber and combining React components with three.js!
Conclusion
React-three-fiber has done an amazing job in creating a utility library that has zero performance issues. This library makes it incredibly easy to build awesome three dimensional worlds in the web. The documentation is really well laid out and makes it easy to get going with this beautiful library. There really is no limit to what you can do with this amazing technology.