React Three Fiber
Three.js in React with R3F, Drei helpers, useFrame, useThree, physics, post-processing.
threejsreact3dr3ffrontend
# React Three Fiber (R3F)
## Setup
```bash
npm install three @react-three/fiber @react-three/drei
```
## Basic scene
```tsx
import { Canvas, useFrame } from '@react-three/fiber'
import { OrbitControls, Environment } from '@react-three/drei'
import { useRef } from 'react'
function Box() {
const ref = useRef<THREE.Mesh>(null)
useFrame((state, delta) => {
if (ref.current) {
ref.current.rotation.x += delta
ref.current.rotation.y += delta * 0.5
}
})
return (
<mesh ref={ref}>
<boxGeometry args={[1, 1, 1]} />
<meshStandardMaterial color="hotpink" />
</mesh>
)
}
export default function App() {
return (
<Canvas camera={{ position: [0, 0, 5], fov: 75 }}>
<ambientLight intensity={0.5} />
<directionalLight position={[5, 5, 5]} />
<Box />
<OrbitControls />
<Environment preset="city" />
</Canvas>
)
}
```
## useFrame & useThree
```tsx
const { camera, gl, scene, clock } = useThree()
useFrame((state, delta) => {
// Runs every frame, inside Canvas only
// state.clock.elapsedTime, state.pointer (normalized mouse)
})
```
## Drei essentials
- `<OrbitControls>` / `<TrackballControls>`
- `<Environment preset="sunset">` -- IBL lighting from HDR
- `<Text font="/font.woff">Hello</Text>` -- 3D text
- `<Html position={[0,1,0]}>` -- DOM in 3D space
- `<useGLTF('/model.glb')>` -- load GLTF with suspense
- `<MeshReflectorMaterial>` -- mirror floor
- `<Sparkles>` -- particle effects
- `<ScrollControls>` -- scroll-based animation
- `<useTexture('/img.jpg')>`
- `<Instances>` / `<InstancedMesh>` for performance
## Loading models
```tsx
import { useGLTF } from '@react-three/drei'
function Model() {
const { scene, animations } = useGLTF('/model.glb')
const { actions } = useAnimations(animations, scene)
useEffect(() => { actions['Idle']?.play() }, [])
return <primitive object={scene} />
}
useGLTF.preload('/model.glb')
```
## Physics (Rapier)
```tsx
import { Physics, RigidBody } from '@react-three/rapier'
<Physics>
<RigidBody>
<mesh><sphereGeometry /><meshStandardMaterial /></mesh>
</RigidBody>
<RigidBody type="fixed">
<mesh><boxGeometry args={[10, 0.1, 10]} /></mesh>
</RigidBody>
</Physics>
```
## Post-processing
```tsx
import { EffectComposer, Bloom, ChromaticAberration, Noise } from '@react-three/postprocessing'
<EffectComposer>
<Bloom luminanceThreshold={0.9} intensity={1.5} />
<ChromaticAberration offset={[0.002, 0.002]} />
</EffectComposer>
```API: /api/skills/react-three-fiber