If you don’t already have a React project, create one:
npx create-react-app my-app
cd my-app
Install @react-three/fiber
, @react-three/drei
, and three
:
npm install @react-three/fiber three @react-three/drei
@react-three/fiber
: React renderer for Three.js.three
: The core Three.js library.@react-three/drei
: Prebuilt helpers for common tasks like cameras, lights, and models.
If you need extra utilities, install three-stdlib
:
npm install three-stdlib
Replace the contents of src/App.js
with the following:
import React from "react";
import { Canvas } from "@react-three/fiber";
import { OrbitControls } from "@react-three/drei";
function Box() {
return (
<mesh>
<boxGeometry args={[1, 1, 1]} />
<meshStandardMaterial color="orange" />
</mesh>
);
}
function App() {
return (
<Canvas>
{/* Add some lighting */}
<ambientLight />
<pointLight position={[10, 10, 10]} />
{/* Add your 3D objects */}
<Box />
{/* Add camera controls */}
<OrbitControls />
</Canvas>
);
}
export default App;
Start your React app:
npm start
You’ll see a rotating orange cube with orbit controls enabled.
Here’s how to extend your setup with common libraries:
To load .glb
or .gltf
models, use useGLTF
from @react-three/drei
:
import { useGLTF } from "@react-three/drei";
function Model() {
const { scene } = useGLTF("/path/to/model.glb");
return <primitive object={scene} />;
}
Make sure the model file is in your public
folder or available via URL.
Enable shadows in your Canvas
and configure materials and lights:
<Canvas shadows>
<ambientLight intensity={0.5} />
<directionalLight
castShadow
position={[5, 5, 5]}
intensity={1}
/>
<mesh castShadow receiveShadow>
<boxGeometry args={[1, 1, 1]} />
<meshStandardMaterial color="orange" />
</mesh>
</Canvas>
To simulate physics, install @react-three/cannon
:
npm install @react-three/cannon
Example usage:
import { Physics, useBox } from "@react-three/cannon";
function PhysicsBox() {
const [ref] = useBox(() => ({ mass: 1, position: [0, 5, 0] }));
return (
<mesh ref={ref}>
<boxGeometry args={[1, 1, 1]} />
<meshStandardMaterial color="blue" />
</mesh>
);
}
<Canvas>
<Physics>
<PhysicsBox />
</Physics>
</Canvas>;
For effects like bloom or depth of field, install:
npm install @react-three/postprocessing
Example:
import { EffectComposer, Bloom } from "@react-three/postprocessing";
<Canvas>
{/* Scene setup */}
<EffectComposer>
<Bloom intensity={1.5} />
</EffectComposer>
</Canvas>;
For larger projects:
- Organize components in folders (e.g.,
src/components/Box.js
). - Create a
useScene.js
orSceneContext
for shared logic.
- Performance Optimizations: Use the
drei
helpers likePreload
,useMemo
, anduseFrame
to optimize rendering. - Debugging Tools: Install
react-three-gui
or enable thereact-three/debug
mode for development. - Documentation and Examples: Refer to the React Three Fiber docs and Three.js examples.