react-three-fiber

安装量: 50
排名: #14986

安装

npx skills add https://github.com/anthemflynn/ccmp --skill react-three-fiber

React Three Fiber

React Three Fiber (R3F) is a React renderer for Three.js. Write declarative, component-based 3D scenes using JSX.

Library Versions (2026)

React Three Fiber: v9.5+ @react-three/drei: v9.116+ @react-three/rapier: v2+ @react-three/postprocessing: v3+ React: 19+ (concurrent features supported) Decision Frameworks When to Use R3F vs Vanilla Three.js Is your app already React-based? → Yes: Use R3F (natural integration) → No: Consider vanilla Three.js

Do you need React state management? → Yes: Use R3F (seamless state integration) → No: Either works

Is the 3D scene the entire app? → Yes: Either works (R3F has slight overhead) → No, mixed with React UI: Use R3F

Performance-critical with millions of objects? → Consider vanilla Three.js for maximum control → R3F is fine for 99% of use cases

When to Use Which State Management Local component state (single mesh color, hover)? → useState / useRef

Shared between few components (selected object)? → React Context or prop drilling

Global game/app state (score, inventory, settings)? → Zustand (recommended for R3F)

Complex state with actions/reducers? → Zustand with slices or Redux Toolkit

Need state persistence? → Zustand with persist middleware

When to Use Which Drei Component Need camera controls? ├─ Orbit around object → OrbitControls ├─ First-person → PointerLockControls ├─ Map/top-down → MapControls └─ Smooth transitions → CameraControls

Need environment lighting? ├─ Quick preset → ├─ Custom HDR → └─ Performance-sensitive →

Need text? ├─ 3D text in scene → ├─ 2D text billboards → └─ HTML overlay →

Need loading? ├─ GLTF models → useGLTF ├─ Textures → useTexture ├─ Progress UI → useProgress └─ Preloading →

Core Setup import { Canvas } from '@react-three/fiber'

function App() { return ( ) }

Canvas Props

{}} // Access internals /> Essential Hooks useFrame - Animation Loop import { useFrame } from '@react-three/fiber' import { useRef } from 'react' function SpinningBox() { const meshRef = useRef() useFrame((state, delta) => { // state: { clock, camera, scene, gl, pointer, ... } meshRef.current.rotation.y += delta meshRef.current.position.y = Math.sin(state.clock.elapsedTime) }) return ( ) } useThree - Access Internals import { useThree } from '@react-three/fiber' function CameraLogger() { const { camera, gl, scene, size, viewport, pointer } = useThree() // viewport: { width, height } in Three.js units // size: { width, height } in pixels // pointer: normalized mouse position (-1 to 1) return null } useLoader - Asset Loading import { useLoader } from '@react-three/fiber' import { TextureLoader } from 'three' import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader' function Model() { const gltf = useLoader(GLTFLoader, '/model.glb') const texture = useLoader(TextureLoader, '/texture.jpg') return } JSX to Three.js Mapping // Three.js class → camelCase JSX element // Constructor args → args prop (array) // Properties → props // THREE.Mesh {/* THREE.BoxGeometry(1, 2, 1) */} {/* THREE.MeshStandardMaterial({ color: 'red' }) */} // Nested properties use dash notation // Attach to parent properties Drei - Essential Helpers Drei provides production-ready abstractions. Install: @react-three/drei import { OrbitControls, PerspectiveCamera, Environment, useGLTF, useTexture, Text, Html, Float, Stage, ContactShadows, Sky, Stars, } from '@react-three/drei' Common Drei Components // Camera controls // Environment lighting (HDR) // Presets: apartment, city, dawn, forest, lobby, night, park, studio, sunset, warehouse // Load GLTF with draco support const { scene, nodes, materials } = useGLTF('/model.glb') useGLTF.preload('/model.glb') // Load textures const [colorMap, normalMap] = useTexture(['/color.jpg', '/normal.jpg']) // 3D Text Hello World // HTML overlay in 3D space

Click me
// Floating animation ... // Quick studio lighting // Soft shadows on ground Event Handling { e.stopPropagation() console.log('clicked', e.point, e.face) }} onPointerOver={(e) => setHovered(true)} onPointerOut={(e) => setHovered(false)} onPointerMove={(e) => console.log(e.point)} onPointerDown={(e) => {}} onPointerUp={(e) => {}} onDoubleClick={(e) => {}} onContextMenu={(e) => {}} > Event object includes: point, face, faceIndex, distance, object, eventObject, camera, ray. State Management With Zustand (Recommended) import { create } from 'zustand' const useStore = create((set) => ({ score: 0, gameState: 'idle', addScore: (points) => set((state) => ({ score: state.score + points })), startGame: () => set({ gameState: 'playing' }), })) function ScoreDisplay() { const score = useStore((state) => state.score) return {score} } function GameLogic() { const addScore = useStore((state) => state.addScore) useFrame(() => { // Game logic that calls addScore }) return null } With React Context const GameContext = createContext() function GameProvider({ children }) { const [state, dispatch] = useReducer(reducer, initialState) return ( {children} ) } // Wrap Canvas content Performance Patterns Instancing import { Instances, Instance } from '@react-three/drei' function Boxes({ count = 1000 }) { return ( {Array.from({ length: count }, (_, i) => ( ))} ) } Selective Rendering // Only re-render when needed {/* Call invalidate() to trigger render */} function Controls() { const { invalidate } = useThree() return invalidate()} /> } Memoization // Memoize expensive components const ExpensiveModel = memo(function ExpensiveModel({ url }) { const gltf = useGLTF(url) return }) // Memoize materials/geometries outside components const geometry = new THREE.BoxGeometry(1, 1, 1) const material = new THREE.MeshStandardMaterial({ color: 'red' }) function Box() { return ( ) } Adaptive Performance import { PerformanceMonitor, AdaptiveDpr, AdaptiveEvents } from '@react-three/drei' setQuality('low')} onIncline={() => setQuality('high')} > Related Skills When you need... Use skill Vanilla Three.js (no React) → threejs Optimize assets before loading → asset-pipeline-3d Debug visual/performance issues → graphics-troubleshooting Reference Files references/drei.md - Complete Drei component reference references/physics.md - @react-three/rapier integration references/postprocessing.md - @react-three/postprocessing effects references/state.md - Zustand patterns for R3F

返回排行榜