Skip to content
Esc

noctcore-three/no-allocation-in-frame-loop

No three.js math objects or GPU resources constructed, or transforms cloned, inside a frame loop.

A frame loop runs 60 to 120 times a second. A new Vector3() in it is thousands of short-lived objects a minute, and the garbage collector pays for them in pauses that show up as dropped frames. A geometry, material or texture built there is worse: each one is uploaded to the GPU and never disposed. Create the object once and reuse it with .set() and .copy():

Incorrect · src/Float.tsx
import * as THREE from 'three';
import { useFrame } from '@react-three/fiber';
export function Float({ mesh }: { mesh: { current: THREE.Mesh } }) {
useFrame(() => {
mesh.current.position.lerp(new THREE.Vector3(0, 1, 0), 0.1);
});
return null;
}
Correct · src/Float.tsx
import * as THREE from 'three';
import { useFrame } from '@react-three/fiber';
const target = new THREE.Vector3(0, 1, 0);
export function Float({ mesh }: { mesh: { current: THREE.Mesh } }) {
useFrame(() => {
mesh.current.position.lerp(target, 0.1);
});
return null;
}

new X() inside a frame loop, where X is imported from three (named, or through import * as THREE) and is either:

  • a math class: Vector2, Vector3, Vector4, Matrix3, Matrix4, Quaternion, Euler, Color, Box2, Box3, Sphere, Ray, Plane, Line3, Triangle, Spherical, Cylindrical, Frustum, Raycaster;
  • a GPU resource: any *Geometry, *Material, *Texture or *RenderTarget class.

It also flags .clone() with no arguments on a transform field of a three.js object, which allocates the same way: mesh.current.position.clone(), camera.quaternion.clone(), dummy.matrixWorld.clone(). The field is one of position, quaternion, rotation, scale, up, matrix, matrixWorld, matrixWorldInverse, projectionMatrix and projectionMatrixInverse, and two things must hold:

  • the object is known to be a three.js one from the file’s own declarations: a variable built with new from a class imported from three.js (also useMemo(() => new THREE.Object3D(), [])), a variable or parameter typed as a three.js type (mesh: THREE.Mesh), ref.current of useRef<THREE.Mesh>(), useRef(new THREE.Group()) or a RefObject<THREE.Mesh>, and the camera and scene React Three Fiber hands out (useFrame(({ camera }) => ...), state.camera, useThree((state) => state.camera), const { scene } = useThree());
  • the call runs on every frame the object exists (see the conditions below).
Incorrect · src/Follow.tsx
import * as THREE from 'three';
import { useFrame } from '@react-three/fiber';
import { useRef } from 'react';
export function Follow({ offset }: { offset: THREE.Vector3 }) {
const mesh = useRef<THREE.Mesh>(null!);
useFrame(({ camera }) => {
camera.position.lerp(mesh.current.position.clone().add(offset), 0.1);
});
return <mesh ref={mesh} />;
}
Correct · src/Follow.tsx
import * as THREE from 'three';
import { useFrame } from '@react-three/fiber';
import { useRef } from 'react';
const target = new THREE.Vector3();
export function Follow({ offset }: { offset: THREE.Vector3 }) {
const mesh = useRef<THREE.Mesh>(null!);
useFrame(({ camera }) => {
camera.position.lerp(target.copy(mesh.current.position).add(offset), 0.1);
});
return <mesh ref={mesh} />;
}

A frame loop is the callback of R3F’s useFrame (imported from @react-three/fiber), the callback of renderer.setAnimationLoop(), or a function that schedules itself with requestAnimationFrame(name) (also requestAnimationFrame(this.name) in a class). Callbacks are matched inline or by reference (setAnimationLoop(tick) resolves tick through scope), and inline callbacks inside the loop (items.forEach(...)) count too.

Incorrect · src/loop.ts
import { Vector3 } from 'three';
function animate() {
requestAnimationFrame(animate);
mesh.position.add(new Vector3(0, 0.01, 0));
renderer.render(scene, camera);
}
animate();
Correct · src/loop.ts
import { Vector3 } from 'three';
const step = new Vector3(0, 0.01, 0);
function animate() {
requestAnimationFrame(animate);
mesh.position.add(step);
renderer.render(scene, camera);
}
animate();
  • Files that import neither three (or a three/* subpath), three-stdlib, an @react-three/* package nor one of extraModules: the rule only runs in three.js code, so another engine’s API with the same names (a Phaser or Babylon camera) is never read as three.js. Only static import declarations count: a file that loads three.js only through import() or require() is skipped, which can hide a report but never adds one.
  • Lazy initialisation that runs once: ref.current ??= new Vector3(), cache.v = cache.v ?? new Vector3() (the result goes back to the target the left side reads), and ref.current = new Vector3() in a branch that runs only while that same target is unset (if (!ref.current), if (ref.current == null), if (typeof ref.current === 'undefined')), or after an early return that fires whenever it is set (if (ref.current) return;, also when that if sits in a bare block above the assignment). A fallback that is not stored back (const v = p.v || new Vector3()) and a guard on another name or with the opposite polarity (if (!ref.current) return;) are still reported. So is a target the same pass empties again after filling it (ref.current = undefined, delete cache.v, or cache = {} for cache.v, as a plain statement after the assignment), because the next frame then initialises it again. An emptying that runs on another pass is not counted: under a branch (if (!dragging) { start.current = null; return; }), before the assignment, behind a return, or in a nested function.
  • A local class or variable that shadows the three.js import where it is used (class Vector3 {} inside the loop).
  • Classes that are not imported from three (a local Vector3 class), and three.js classes that are neither math nor GPU resources (Group, Object3D).
  • A one-shot requestAnimationFrame(() => ...), and a helper function declared inside the loop.
  • .clone() on anything the file does not show to be a three.js object. Without type information the rule cannot tell a Vector3 from anything else with a clone() method, so the field name alone proves nothing: keys.up.clone(), player.position.clone() on an untyped prop or store value, ref.current.position.clone() on useRef(null), a field of a call result or an indexed element (pick().position.clone(), meshes[i].position.clone()), a this.mesh field and a destructured prop typed on the pattern are all left alone. Other fields (velocity.clone(), controls.target.clone()) and a bare position.clone() are too.
  • .clone() that runs only on some frames: under an if, a ? :, the right side of && / || / ?? or a switch case, or after an early return on such a condition (if (pressed) start = camera.position.clone() and if (!pressed.current) return; start = camera.position.clone() are the same code). A snapshot taken when something happens is not a per-frame cost; a clone that runs on every frame while a flag is set is missed for the same reason. A check that only asks whether the cloned object is there is not a condition: if (!mesh.current) return;, if (mesh.current) { ... } and mesh.current && ... around mesh.current.position.clone() are still reported. A check on another object, or one mixed with something else (if (!mesh.current || paused) return;), is a condition.
  • A clone stored once (home.current ??= mesh.current.position.clone()), which is lazy initialisation like any other.
Correct · src/Float.tsx
import * as THREE from 'three';
import { useFrame } from '@react-three/fiber';
export function Float({ mesh, target }: { mesh: { current: THREE.Mesh }; target: { current?: THREE.Vector3 } }) {
useFrame(() => {
target.current ??= new THREE.Vector3(0, 1, 0);
mesh.current.position.lerp(target.current, 0.1);
});
return null;
}
Option Type Default Meaning
allowIn string[] (globs) [] Files the rule skips, matched against the absolute path and the path relative to the working directory or workspace root.
extraModules string[] [] More module specifiers that mark a file as three.js code (a project module that re-exports three.js, such as @acme/engine); subpaths match too, and their imports count as three.js classes and R3F hooks.
'noctcore-three/no-allocation-in-frame-loop': ['error', { allowIn: ['**/demos/**'] }]

Code whose loop runs rarely (a frameloop="demand" canvas that renders on interaction only) gains little from hoisting, though it costs nothing either.