TExcelTAD
Home › 3D Web Games with Three.js › React Three Fiber & drei

React Three Fiber & drei

React Three Fiber (R3F, package @react-three/fiber) is a React renderer for Three.js: instead of creating objects with new and adding them with scene.add, you describe the scene as JSX components, and R3F creates, updates and disposes the Three.js objects for you. It comes from the pmndrs (Poimandres) collective, which also maintains a large ecosystem around it: drei (ready-made helpers), @react-three/rapier (physics), @react-three/postprocessing, leva (debug GUI) and zustand (state). If your team already builds its UI in React, R3F is the most popular way to make 3D web apps and games.

The playgrounds here can run React, but not R3F (it isn't in the site's import map), so the R3F code in this lesson is shown, not run.

Versions

At the time of writing: @react-three/fiber 9.x (for React 19), @react-three/drei 10.x, @react-three/rapier 2.x. Fiber 8 pairs with React 18. R3F has no pinned Three.js version of its own; it uses the three package you install, so the r186 knowledge from this course applies directly.

bash
npm create vite@latest my-r3f-game -- --template react-ts
cd my-r3f-game
npm install three @react-three/fiber @react-three/drei
npm install -D @types/three

The same scene, two ways

Plain Three.js, as in the rest of this course:

js
const renderer = new THREE.WebGLRenderer({ antialias: true });
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(50, innerWidth / innerHeight, 0.1, 100);
camera.position.set(0, 2, 5);
const box = new THREE.Mesh(new THREE.BoxGeometry(), new THREE.MeshStandardMaterial({ color: 'orange' }));
scene.add(box, new THREE.AmbientLight('#fff', 0.5));
renderer.setAnimationLoop((t) => { box.rotation.y = t / 1000; renderer.render(scene, camera); });

React Three Fiber:

jsx
import { Canvas, useFrame } from '@react-three/fiber';
import { OrbitControls } from '@react-three/drei';
import { useRef, useState } from 'react';

function SpinningBox(props) {
  const ref = useRef();
  const [hovered, setHovered] = useState(false);
  useFrame((state, delta) => { ref.current.rotation.y += delta; });   // runs every frame, outside React rendering
  return (
    <mesh {...props} ref={ref}
      onPointerOver={() => setHovered(true)} onPointerOut={() => setHovered(false)}>
      <boxGeometry args={[1, 1, 1]} />
      <meshStandardMaterial color={hovered ? 'hotpink' : 'orange'} />
    </mesh>
  );
}

export default function App() {
  return (
    <Canvas camera={{ position: [0, 2, 5], fov: 50 }} dpr={[1, 2]} shadows>
      <ambientLight intensity={0.5} />
      <directionalLight position={[3, 5, 2]} intensity={2} castShadow />
      <SpinningBox position={[0, 0.5, 0]} />
      <OrbitControls />
    </Canvas>
  );
}

How the JSX maps to Three.js:

R3F Three.js
<mesh position={[0, 0.5, 0]}> new THREE.Mesh(), mesh.position.set(0, 0.5, 0)
<boxGeometry args={[1, 1, 1]} /> new THREE.BoxGeometry(1, 1, 1) attached as mesh.geometry
<meshStandardMaterial color="orange" /> new THREE.MeshStandardMaterial({ color: 'orange' }) attached as mesh.material
<Canvas> renderer, scene, camera, render loop, resize handling (with a dpr range, color management and tone mapping set up for you)
useFrame((state, delta) => …) code in the animation loop
onClick, onPointerOver on meshes a built-in raycaster (Pointer Raycasting)
unmounting a component removes the object and disposes what R3F created

drei: the helpers you'd otherwise write

Helper Does
<OrbitControls />, <PointerLockControls />, <CameraControls /> the controls from this course as components
useGLTF(url) (+ useGLTF.preload) loads glTF with DRACO/meshopt support and caching; works with React Suspense
useAnimations(clips, ref) an AnimationMixer with named actions
<Environment preset="sunset" />, <Sky />, <Stars /> environment maps and skies
<Html> DOM elements positioned at a 3D point (labels, nameplates)
<Text> crisp SDF text in 3D (troika-three-text)
<Instances> / <Instance> instancing with a component per instance
<KeyboardControls> + useKeyboardControls action-mapped keyboard input
<Detailed>, <BakeShadows>, <AdaptiveDpr>, <PerformanceMonitor> LOD and performance helpers
<Stats>, <Grid>, <GizmoHelper> debugging

Physics with @react-three/rapier wraps Rapier (Physics with Rapier) the same way:

jsx
import { Physics, RigidBody, CuboidCollider } from '@react-three/rapier';

<Physics gravity={[0, -9.81, 0]}>
  <RigidBody colliders="ball" restitution={0.7}>
    <mesh position={[0, 4, 0]}><sphereGeometry args={[0.5]} /><meshStandardMaterial /></mesh>
  </RigidBody>
  <RigidBody type="fixed"><CuboidCollider args={[10, 0.1, 10]} /></RigidBody>
</Physics>

The rule for games: don't re-render every frame

React re-renders a component when its state changes, which means running the component function, diffing and reconciling: fine a few times per second, far too slow 60 times per second for hundreds of objects. In R3F, things that change every frame must be mutated directly inside useFrame, through refs, never pushed through useState. This small React demo (it runs; it's plain React DOM, no 3D) shows the difference: both boxes move the same way, but one goes through state and re-renders on every frame, while the other mutates its element through a ref.

jsx · try it yourself
import { useEffect, useRef, useState } from 'react';

function ViaState() {
  const [x, setX] = useState(0);
  const renders = useRef(0);
  renders.current++;
  useEffect(() => {
    let id;
    const tick = (t) => { setX((Math.sin(t / 500) + 1) * 100); id = requestAnimationFrame(tick); };
    id = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(id);
  }, []);
  return <Row label="setState every frame" x={x} renders={renders.current} color="#ef5350" />;
}

function ViaRef() {
  const box = useRef(null);
  const renders = useRef(0);
  renders.current++;
  useEffect(() => {
    let id;
    const tick = (t) => { box.current.style.transform = `translateX(${(Math.sin(t / 500) + 1) * 100}px)`; id = requestAnimationFrame(tick); };
    id = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(id);
  }, []);
  return <Row label="mutate a ref (like useFrame)" boxRef={box} renders={renders.current} color="#66bb6a" />;
}

function Row({ label, x = 0, renders, color, boxRef }) {
  return (
    <div style={{ margin: '12px 0', fontFamily: 'system-ui, sans-serif', fontSize: 13 }}>
      <div>{label}: <b>{renders}</b> React renders</div>
      <div style={{ position: 'relative', height: 24, width: 240, background: '#eee', borderRadius: 4 }}>
        <div ref={boxRef} style={{ position: 'absolute', width: 24, height: 24, borderRadius: 4, background: color, transform: `translateX(${x}px)` }} />
      </div>
    </div>
  );
}

export default function App() {
  return <><ViaState /><ViaRef /></>;
}

The red row's render count climbs by about 60 per second; the green row renders once. In R3F the same applies: useFrame((_, dt) => { ref.current.position.x += speed * dt }) is right, const [x, setX] = useState(0) updated in useFrame is the classic performance bug. Keep game state that changes every frame in plain objects or a zustand store read with getState() inside useFrame, and use React state for things that change rarely (score display, menus).

When to choose R3F

Choose R3F when Choose plain Three.js when
the game lives inside a React app (configurators, portfolio sites, UI-heavy games) the game is the whole page and has little HTML UI
you want drei's helpers and the pmndrs ecosystem you want full control of the loop and object lifetimes
the team knows React well you are learning how Three.js works (this course)
you target the smallest bundle and the least overhead

Everything you learned here transfers: R3F is Three.js. Materials, lights, color management, shadows, instancing, LOD and the performance rules are identical; R3F only changes how you create and organise the objects. The docs at r3f.docs.pmnd.rs and the drei README are the references.

Test yourself

In R3F, what does <boxGeometry args={[1, 2, 3]} /> inside a <mesh> create?

  1. A React DOM element
  2. new THREE.BoxGeometry(1, 2, 3), attached as the mesh's geometry
  3. A physics collider
  4. A drei helper

A character's position is stored with useState and updated in useFrame. What is the problem?

  1. useFrame can't read state
  2. The component re-renders 60+ times per second; mutate the object through a ref instead
  3. Positions must be quaternions
  4. There is no problem

Which package provides useGLTF, <Environment> and <OrbitControls> for R3F?

  1. @react-three/rapier
  2. @react-three/drei
  3. zustand
  4. leva