BjornMelin/dev-skills / plugins/web-motion/skills/web-three-r3f
web-three-r3f
VerifiedUse this skill for Three.js, React Three Fiber, Drei, Canvas/createRoot lifecycle, loaders, GLTF, useFrame, disposal, SSR/client boundaries, DPR, and browser proof. Trigger on Three.js, THREE, @react-three/fiber, @react-three/drei, R3F Canvas, useFrame, GLTF, WebGLRenderer. Do not use for near-miss tasks outside these boundaries; route to adjacent motion or platform skills when they own the implementation.
references/docs-r3f-pitfalls.md
View on GitHub[r3fReact Three Fiber](https://r3f.docs.pmnd.rs/). [docs](https://docs.pmnd.rs/)
Search for anythingPress `/` to search
# Performance pitfalls
Performance 1x1
[**Tips and Tricks**](https://r3f.docs.pmnd.rs/advanced/pitfalls#tips-and-tricks)
This is a good overview: [https://discoverthreejs.com/tips-and-tricks](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:
```jsx
const geom = useMemo(() => new BoxGeometry(), [])
const mat = useMemo(() => new MeshBasicMaterial(), [])
return items.map(i => <mesh geometry={geom} material={mat} ...
```
Try to use [instancing](https://codesandbox.io/s/r3f-instanced-colors-8fo01) as much as you can when you need to display many objects of a similar type!
[**Avoid setState in loops**](https://r3f.docs.pmnd.rs/advanced/pitfalls#avoid-setstate-in-loops)
TLDR, don't, mutate inside `useFrame`!
- Threejs has a render-loop, it does not work like the DOM does. **Fast updates are carried out in `useFrame` by mutation**. `useFrame` is your per-component render-loop.
- It is not enough to set values in succession, _you need frame deltas_. Instead of `position.x += 0.1` consider `position.x += delta` or your project will run at different speeds depending on the end-users system. Many updates in threejs need to be paired with update flags (`.needsUpdate = true`), or imperative functions (`.updateProjectionMatrix()`).
- You might be tempted to setState inside `useFrame` but there is no reason to. You would only complicate something as simple as an update by routing it through React's scheduler, triggering component render etc.
[**❌ `setState` in loops is bad**](https://r3f.docs.pmnd.rs/advanced/pitfalls#%E2%9D%8C-setstate-in-loops-is-bad)
```jsx
useEffect(() => {
const interval = setInterval(() => setX((x) => x + 0.1), 1)
return () => clearInterval(interval)
}, [])
```
[**❌ `setState` in useFrame is bad**](https://r3f.docs.pmnd.rs/advanced/pitfalls#%E2%9D%8C-setstate-in-useframe-is-bad)
```jsx
const [x, setX] = useState(0)
useFrame(() => setX((x) => x + 0.1))
return <mesh position-x={x} />
```
[**❌ `setState` in fast events is bad**](https://r3f.docs.pmnd.rs/advanced/pitfalls#%E2%9D%8C-setstate-in-fast-events-is-bad)
```jsx
<mesh onPointerMove={(e) => setX((x) => e.point.x)} />
```
[**✅ Instead, just mutate, use deltas**](https://r3f.docs.pmnd.rs/advanced/pitfalls#%E2%9C%85-instead,-just-mutate,-use-deltas)
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!
```jsx
const meshRef = useRef()
useFrame((state, delta) => (meshRef.current.position.x += delta))
return <mesh ref={meshRef} />
```
Same goes for events, use references.
```jsx
<mesh onPointerMove={(e) => (ref.current.position.x = e.point.x)} />
```
If you must use intervals, use references as well, but keep in mind that this is not refresh-rate independent.
```jsx
useEffect(() => {
const interval = setInterval(() => ref.current.position.x += 0.1, 1)
return () => clearInterval(interval)
}, [])
```
[**Handle animations in loops**](https://r3f.docs.pmnd.rs/advanced/pitfalls#handle-animations-in-loops)
The frame loop is where you should place your animations. For instance using lerp, or damp.
[**✅ Use `lerp` \+ `useFrame`**](https://r3f.docs.pmnd.rs/advanced/pitfalls#%E2%9C%85-use-lerp-+-useframe)
```jsx
function Signal({ active }) {
const meshRef = useRef()
useFrame((state, delta) => {
meshRef.current.position.x = THREE.MathUtils.lerp(meshRef.current.position.x, active ? 100 : 0, 0.1)
})
return <mesh ref={meshRef} />
```
[**✅ Or react-spring**](https://r3f.docs.pmnd.rs/advanced/pitfalls#%E2%9C%85-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.
```jsx
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**](https://r3f.docs.pmnd.rs/advanced/pitfalls#do-not-bind-to-fast-state-reactively)
Using state-managers and selective state is fine, but not for updates that happen rapidly for the same reason as above.
[**❌ Don't bind reactive fast-state**](https://r3f.docs.pmnd.rs/advanced/pitfalls#%E2%9D%8C-don't-bind-reactive-fast-state)
```jsx
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**](https://r3f.docs.pmnd.rs/advanced/pitfalls#%E2%9C%85-fetch-state-directly)
For instance using [Zustand](https://github.com/pmndrs/zustand) (same in Redux et al).
```jsx
useFrame(() => (ref.current.position.x = api.getState().x))
return <mesh ref={ref} />
```
[**Don't mount indiscriminately**](https://r3f.docs.pmnd.rs/advanced/pitfalls#don't-mount-indiscriminately)
In threejs it is very common to not re-mount at all, see the ["disposing of things"](https://discoverthreejs.com/tips-and-tricks/) section in discover-three. This is because buffers and materials get re-initialized/compiled, which can be expensive.
[**❌ Avoid mounting runtime**](https://r3f.docs.pmnd.rs/advanced/pitfalls#%E2%9D%8C-avoid-mounting-runtime)
```jsx
{
stage === 1 && <Stage1 />
}
{
stage === 2 && <Stage2 />
}
{
stage === 3 && <Stage3 />
}
```
[**✅ Consider using visibility instead**](https://r3f.docs.pmnd.rs/advanced/pitfalls#%E2%9C%85-consider-using-visibility-instead)
```jsx
<Stage1 visible={stage === 1} />
<Stage2 visible={stage === 2} />
<Stage3 visible={stage === 3} />
function Stage1(props) {
return (
<group {...props}>
...
```
[**✅ Use `startTransition` for expensive ops**](https://r3f.docs.pmnd.rs/advanced/pitfalls#%E2%9C%85-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](https://github.com/drcmda/scheduler-test) and see if marking ops with a lesser priority makes a difference.
```jsx
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**](https://r3f.docs.pmnd.rs/advanced/pitfalls#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**](https://r3f.docs.pmnd.rs/advanced/pitfalls#%E2%9D%8C-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.
```jsx
useFrame(() => {
ref.current.position.lerp(new THREE.Vector3(x, y, z), 0.1)
})
```
[**✅ Better re-use object**](https://r3f.docs.pmnd.rs/advanced/pitfalls#%E2%9C%85-better-re-use-object)
Set up re-used objects in global or local space, now the GC will be silent.
```jsx
function Foo(props)
const vec = new THREE.Vector()
useFrame(() => {
ref.current.position.lerp(vec.set(x, y, z), 0.1)
})
```
[**`useLoader` instead of plain loaders**](https://r3f.docs.pmnd.rs/advanced/pitfalls#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**](https://r3f.docs.pmnd.rs/advanced/pitfalls#%E2%9D%8C-no-re-use-is-bad-for-perf)
This re-fetches, re-parses for every component instance.
```jsx
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**](https://r3f.docs.pmnd.rs/advanced/pitfalls#%E2%9C%85-cache-and-re-use-objects)
```jsx
function Component() {
const texture = useLoader(TextureLoader, url)
return (
<mesh>
<sphereGeometry />
<meshBasicMaterial map={texture} />
</mesh>
)
}
```
Regarding GLTF's try to use [GLTFJSX](https://github.com/pmndrs/gltfjsx) as much as you can, this will create immutable JSX graphs which allow you to even re-use full models.
[Edit this page](https://github.com/pmndrs/react-three-fiber/edit/master/docs/advanced/pitfalls.mdx)
Previous
[Scaling performance](https://r3f.docs.pmnd.rs/advanced/scaling-performance)
Next
[v9 Migration Guide](https://r3f.docs.pmnd.rs/tutorials/v9-migration-guide)
- [getting started](https://r3f.docs.pmnd.rs/getting-started/introduction)
- [api](https://r3f.docs.pmnd.rs/api/canvas)
- [advanced](https://r3f.docs.pmnd.rs/advanced/scaling-performance)
- [Scaling performance](https://r3f.docs.pmnd.rs/advanced/scaling-performance)
- [Performance pitfalls](https://r3f.docs.pmnd.rs/advanced/pitfalls)
- [tutorials](https://r3f.docs.pmnd.rs/tutorials/v9-migration-guide)
On This Page
#### [Tips and Tricks](https://r3f.docs.pmnd.rs/advanced/pitfalls\#tips-and-tricks)
#### [Avoid setState in loops](https://r3f.docs.pmnd.rs/advanced/pitfalls\#avoid-setstate-in-loops)
#### [❌ setState in loops is bad](https://r3f.docs.pmnd.rs/advanced/pitfalls\#%E2%9D%8C-setstate-in-loops-is-bad)
#### [❌ setState in useFrame is bad](https://r3f.docs.pmnd.rs/advanced/pitfalls\#%E2%9D%8C-setstate-in-useframe-is-bad)
#### [❌ setState in fast events is bad](https://r3f.docs.pmnd.rs/advanced/pitfalls\#%E2%9D%8C-setstate-in-fast-events-is-bad)
#### [✅ Instead, just mutate, use deltas](https://r3f.docs.pmnd.rs/advanced/pitfalls\#%E2%9C%85-instead,-just-mutate,-use-deltas)
#### [Handle animations in loops](https://r3f.docs.pmnd.rs/advanced/pitfalls\#handle-animations-in-loops)
#### [✅ Use lerp + useFrame](https://r3f.docs.pmnd.rs/advanced/pitfalls\#%E2%9C%85-use-lerp-+-useframe)
#### [✅ Or react-spring](https://r3f.docs.pmnd.rs/advanced/pitfalls\#%E2%9C%85-or-react-spring)
#### [Do not bind to fast state reactively](https://r3f.docs.pmnd.rs/advanced/pitfalls\#do-not-bind-to-fast-state-reactively)
#### [❌ Don't bind reactive fast-state](https://r3f.docs.pmnd.rs/advanced/pitfalls\#%E2%9D%8C-don't-bind-reactive-fast-state)
#### [✅ Fetch state directly](https://r3f.docs.pmnd.rs/advanced/pitfalls\#%E2%9C%85-fetch-state-directly)
#### [Don't mount indiscriminately](https://r3f.docs.pmnd.rs/advanced/pitfalls\#don't-mount-indiscriminately)
#### [❌ Avoid mounting runtime](https://r3f.docs.pmnd.rs/advanced/pitfalls\#%E2%9D%8C-avoid-mounting-runtime)
#### [✅ Consider using visibility instead](https://r3f.docs.pmnd.rs/advanced/pitfalls\#%E2%9C%85-consider-using-visibility-instead)
#### [✅ Use startTransition for expensive ops](https://r3f.docs.pmnd.rs/advanced/pitfalls\#%E2%9C%85-use-starttransition-for-expensive-ops)
#### [Don't re-create objects in loops](https://r3f.docs.pmnd.rs/advanced/pitfalls\#don't-re-create-objects-in-loops)
#### [❌ Bad news for the GC](https://r3f.docs.pmnd.rs/advanced/pitfalls\#%E2%9D%8C-bad-news-for-the-gc)
#### [✅ Better re-use object](https://r3f.docs.pmnd.rs/advanced/pitfalls\#%E2%9C%85-better-re-use-object)
#### [useLoader instead of plain loaders](https://r3f.docs.pmnd.rs/advanced/pitfalls\#useloader-instead-of-plain-loaders)
#### [❌ No re-use is bad for perf](https://r3f.docs.pmnd.rs/advanced/pitfalls\#%E2%9D%8C-no-re-use-is-bad-for-perf)
#### [✅ Cache and re-use objects](https://r3f.docs.pmnd.rs/advanced/pitfalls\#%E2%9C%85-cache-and-re-use-objects)Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis. | Stars: 472k | Updated | Claude CodeCodex | Verified | Install |
| diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness. | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependencies | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |