Pmndrs.docs

Performance pitfalls

Performance 1x1

Tips and Tricks

This is a good overview: https://discoverthreejs.com/tips-and-tricks

The most important gotcha in three.js is that creating objects can be expensive, think twice before you mount/unmount things! Every material or light that you put into the scene has to compile, every geometry you create will be processed. Share materials and geometries if you can, either in global scope or locally:

const geom = useMemo(() => new BoxGeometry(), [])
const mat = useMemo(() => new MeshBasicMaterial(), [])
return items.map(i => <mesh geometry={geom} material={mat} ...

Try to use instancing as much as you can when you need to display many objects of a similar type!

Avoid setState in loops

SetState in React is not suitable for fast updates, for instance in order to move or animate something, or even if you receive fast data from somewhere: remote, events, etc.

It becomes less of an issue if you think of your app as running in a loop. Threejs is fundamentally loop based. This is because in order to carry out re-curring operations it is not enough to just set a value, you need deltas, needsUpdate, imperative functions, and so on.

❌ setState in loops is bad

const [x, setX] = useState(0)
useFrame(() => setX((x) => x + 0.1))
return <mesh position-x={x} />

❌ setState in fast intervals is bad

useEffect(() => {
  const interval = setInterval(() => setX((x) => x + 0.1), 1)
  return () => clearInterval(interval)
}, [])

❌ setState in fast events is bad

<mesh onPointerMove={(e) => setX((x) => e.point.x)} />

✅ Instead, use refs and mutate

In general you should prefer useFrame! Consider mutating props safe as long as the component is the only entity that mutates. Use deltas instead of fixed values so that your app is refresh-rate independent and runs at the same speed everywhere!

const ref = useRef()
useFrame((state, delta) => (ref.current.position.x += delta))
return <mesh ref={ref} />

As for for intervals and events, just use references!

useEffect(() => {
  const interval = setInterval(() => ref.current.position.x += 0.1), 1)
  return () => clearInterval(interval)
}, [])
<mesh onPointerMove={(e) => (ref.current.position.x = e.point.x)} />

Handle animations in loops

The frame loop is where you should place your animations. For instance using lerp, or damp.

✅ Use lerp + useFrame

function Signal({ active }) {
  const ref = useRef()
  useFrame((state, delta) => {
    ref.current.position.x = THREE.MathUtils.lerp(ref.current.position.x, active ? 100 : 0, 0.1)
  })
  return <mesh ref={ref} />

✅ Or react-spring

Or, use animation libraries. React-spring has its own frame-loop and animates outside of React. Framer-motion is another popular alternative.

import { a, useSpring } from '@react-spring/three'

function Signal({ active }) {
  const { x } = useSpring({ x: active ? 100 : 0 })
  return <a.mesh position-x={x} />

Do not bind to fast state reactively

Using state-managers and selective state is fine, but not for updates that happen rapidly!

❌ Don't bind reactive fast-state

import { useSelector } from 'react-redux'

// Assuming that x gets animated inside the store 60fps
const x = useSelector((state) => state.x)
return <mesh position-x={x} />

✅ Fetch state directly

For instance using Zustand.

useFrame(() => (ref.current.position.x = api.getState().x))
return <mesh ref={ref} />

✅ Or, subscribe transiently

See: transient updates for often occurring state changes.

const ref = useRef()
useEffect(() => {
  api.subscribe(
    (state) => state.x,
    (x) => (ref.current.position.x = x),
  )
}, [])
return <mesh ref={ref} />

Don't mount indiscriminately

In threejs it is very common to not re-mount at all, see the "disposing of things" section in discover-three. This is because buffers and materials get re-initialized/compiled, which can be expensive.

❌ Avoid mounting runtime

{
  stage === 1 && <Stage1 />
}
{
  stage === 2 && <Stage2 />
}
{
  stage === 3 && <Stage3 />
}

✅ Consider using visibility instead

<Stage1 visible={stage === 1} />
<Stage2 visible={stage === 2} />
<Stage3 visible={stage === 3} />

function Stage1(props) {
  return (
    <group {...props}>
      ...

✅ Use startTransition for expensive ops

React 18 introduces the startTransition and useTransition APIs to defer and schedule work and state updates. Use these to de-prioritize expensive operations.

Since version 8 of Fiber canvases use concurrent mode by default, which means React will schedule and defer expensive operations. You don't need to do anything, but you can play around with the experimental scheduler and see if marking ops with a lesser priority makes a difference.

import { useTransition } from 'react'
import { Points } from '@react-three/drei'

const [isPending, startTransition] = useTransition()
const [radius, setRadius] = useState(1)
const positions = calculatePositions(radius)
const colors = calculateColors(radius)
const sizes = calculateSizes(radius)

<Points
  positions={positions}
  colors={colors}
  sizes={sizes}
  onPointerOut={() => {
    startTransition(() => {
      setRadius(prev => prev + 1)
    })
  }}
>
  <meshBasicMaterial vertexColors />
</Points>

Don't re-create objects in loops

Try to avoid creating too much effort for the garbage collector, re-pool objects when you can!

❌ Bad news for the GC

This creates a new vector 60 times a second, which allocates memory and forces the GC to eventually kick in.

useFrame(() => {
  ref.current.position.lerp(new THREE.Vector3(x, y, z), 0.1)
})

✅ Better re-use object

Set up re-used objects in global or local space, now the GC will be silent.

function Foo({ vec = new THREE.Vector(), ...props })
  useFrame(() => {
    ref.current.position.lerp(vec.set(x, y, z), 0.1)
  })

useLoader instead of plain loaders

Threejs loaders give you the ability to load async assets (models, textures, etc), but if you do not re-use assets it can quickly become problematic.

❌ No re-use is bad for perf

This re-fetches, re-parses for every component instance.

function Component() {
  const [texture, set] = useState()
  useEffect(() => void new TextureLoader().load(url, set), [])
  return texture ? (
    <mesh>
      <sphereGeometry />
      <meshBasicMaterial map={texture} />
    </mesh>
  ) : null
}

Instead use useLoader, which caches assets and makes them available throughout the scene.

✅ Cache and re-use objects

function Component() {
  const texture = useLoader(TextureLoader, url)
  return (
    <mesh>
      <sphereGeometry />
      <meshBasicMaterial map={texture} />
    </mesh>
  )
}

Regarding GLTF's try to use GLTFJSX as much as you can, this will create immutable JSX graphs which allow you to even re-use full models.