How I keep a React Three Fiber scroll animation fast
How I kept scroll state outside React in vennee.dev's earlier 3D cube homepage, deferred the scene and reduced GPU work on phones.
An earlier vennee.dev homepage had a 3x3x3 cube behind the content that morphed for each section as you scrolled and did Rubik turns when left alone. Building it took less time than making it smooth on a real phone. I was on Next.js 16.2, React 19.2, three 0.183, @react-three/fiber 9.5 and @react-three/drei 10.7.
Scroll state stays out of React
If the hero re-renders because the cube moved, I've broken something. The cube needs the current section and the scroll depth, and the rest of the page doesn't care.
Sections go through a tiny event bus, a CustomEvent on window with one emit function. An IntersectionObserver fires it when the dominant section changes, and project rows fire it on hover. The camera rig, lighting rig and cube each listen and write into their own ref.
// spatial/events.ts
export const SPATIAL_EVENT = "portfolio-spatial-state";
export type SpatialSection = "hero" | "foundation" | "logic" | "extrusion" | "system";
export type SpatialEventDetail = {
mode: "ambient" | "section" | "project-focus";
section?: SpatialSection;
projectIndex?: number;
};
export function emitSpatialState(detail: SpatialEventDetail) {
if (typeof window === "undefined") return;
window.dispatchEvent(new CustomEvent(SPATIAL_EVENT, { detail }));
}
// HomeContent.tsx ("use client")
useEffect(() => {
const observer = new IntersectionObserver((entries) => {
const active = entries
.filter((entry) => entry.isIntersecting)
.sort((a, b) => b.intersectionRatio - a.intersectionRatio)[0];
if (active) emitSpatialState({ mode: "section", section: active.target.id as SpatialSection });
}, { rootMargin: "-20% 0px -35%", threshold: [0.15, 0.35, 0.55, 0.75] });
SECTION_IDS.forEach((id) => {
const el = document.getElementById(id);
if (el) observer.observe(el);
});
return () => observer.disconnect();
}, []);
In a bigger app I'd use Zustand with transient subscriptions. Here it's one page with three listeners, and window events don't re-render anything. I solved a similar problem with signals in the GSAP ScrollTrigger post. For scroll depth, the frame loop reads window.scrollY itself.
Motion goes in useFrame
Listeners write to refs, and useFrame reads those refs and mutates Three.js objects directly. Here's the camera rig, trimmed:
export function SpatialCameraRig() {
const camera = useThree((s) => s.camera);
const section = useRef<SpatialSection>("hero");
const desiredTarget = useRef(new THREE.Vector3());
const smoothedTarget = useRef(new THREE.Vector3());
useEffect(() => {
const onState = (e: Event) => {
const { section: next, mode, projectIndex } = (e as CustomEvent<SpatialEventDetail>).detail;
if (next) section.current = next;
const focused = mode === "project-focus" && projectIndex !== undefined;
const offset = focused ? THREE.MathUtils.clamp((projectIndex - 2.5) * 0.18, -0.45, 0.45) : 0;
desiredTarget.current.set(offset, 0, 0);
};
window.addEventListener(SPATIAL_EVENT, onState);
return () => window.removeEventListener(SPATIAL_EVENT, onState);
}, []);
useFrame((_, delta) => {
camera.position.lerp(SECTION_POSITIONS[section.current], 1 - Math.exp(-delta * 3.5));
smoothedTarget.current.lerp(desiredTarget.current, 1 - Math.exp(-delta * 3.2));
camera.lookAt(smoothedTarget.current);
}, -1);
return null;
}
The -1 is the callback priority: R3F runs callbacks in ascending order, and the camera moves before the cube. A positive priority would tell R3F you're taking over rendering yourself.
The earlier version damped the camera position but not the look-at target, and hovering a project then scrolling made the view jump sideways for a frame. Now there's a desired target and a smoothed one.
The cube is 27 pieces in one instancedMesh, one draw call. Each frame builds matrices on a reused Object3D and calls setMatrixAt and setColorAt, with temp vectors allocated once up front. When the page is idle, the callback returns early.
Damping used to add a fixed factor per frame:
// before: the speed depends on the refresh rate
group.position.x = THREE.MathUtils.lerp(group.position.x, targetX, 0.03);
// after: the same feel at 60 Hz and 120 Hz
const flow = 1 - Math.exp(-delta * 2.2);
group.position.x = THREE.MathUtils.lerp(group.position.x, targetX, flow);
At 0.03 per frame, a 120 Hz screen reaches the target almost twice as fast as a 60 Hz one. Position, rotation and camera damping now go through delta. A few smaller lerps, like the manual rotation easing back to rest, still use a fixed factor per frame.
The scroll stops for the five layouts used to be hardcoded as [0.04, 0.2, 0.4, 0.7, 0.91], and a section that changed height pulled the cube out of sync. The stops are now measured from the sections, again on ResizeObserver reports and after document.fonts.ready.
Defer the canvas so hero text paints first
The 3D part skips the server and the first JS chunk. The home component imports the background wrapper with ssr: false (Next 16 only allows that in a Client Component), and the wrapper imports the scene through a second dynamic() call, putting three, R3F and drei in their own chunk.
// HomeContent.tsx ("use client")
const TechCubeBackground = dynamic(() => import("@/modules/home/TechCubeBackground").then((m) => m.TechCubeBackground), { ssr: false });
// TechCubeBackground.tsx
const TechCubeScene = dynamic(() => import("./TechCubeScene").then((m) => m.TechCubeScene), { ssr: false, loading: () => null });
export function TechCubeBackground({ isLoaded }: { isLoaded: boolean }) {
// Safe to read navigator during render: with ssr: false there's no server HTML to mismatch.
const lite = typeof window !== "undefined"
&& (isLikelyBotUserAgent(navigator.userAgent) || isMobileOrLowPowerDevice(navigator.userAgent));
const [mounted, setMounted] = useState(false);
useEffect(() => {
if (lite && !isLoaded) return;
const timer = window.setTimeout(() => setMounted(true), lite ? 120 : 800);
return () => window.clearTimeout(timer);
}, [isLoaded, lite]);
if (!mounted) return null;
return lite ? <div className="lite-cube-placeholder" aria-hidden="true" /> : <TechCubeScene />;
}
On desktop the scene mounts 800 ms after hydration so the hero text paints first. The canvas is position: fixed with pointer-events: none under the content.
A Lighthouse 13.4 report in the repo (lh-prod-mobile.json, emulated Moto G Power, local build) shows the plain HTML hero h1 as the Largest Contentful Paint (LCP) element, with a score of 74 and an LCP of 5.6 s. That LCP isn't good, and it's a lab number from before the phone changes below.
Weak devices get less GPU work
Update: when I wrote this, phones and low-power devices skipped WebGL entirely. A later version ran a lite cube on phones at a DPR of 1.5 to 2, and only devices without a real GPU (found by probing the renderer in a Web Worker) skipped it. Details in PageSpeed gave my site 25 on mobile. My own Lighthouse said 90+.
The original isMobileOrLowPowerDevice swapped the Canvas for a CSS placeholder on a mobile user agent, a viewport of 767 px or less, deviceMemory or hardwareConcurrency of 4 or less, or a 2g/3g connection. It's blunt. I'd still rather a decent laptop miss the cube than a cheap Android phone choke on it.
On desktop the Canvas runs with dpr={[1, 1.5]}, and drei's PerformanceMonitor drops DPR to 1 when the frame rate sags. Reflections come from a <Environment resolution={128}> of three Lightformers, whose cube map renders once by default (frames={1}).
With prefers-reduced-motion on, the cube stops breathing and wobbling and Lenis never starts. The random Rubik turns still run, because the check that allows them ignores the flag.
The loader, crawlers and deferred sections
The loader is a full-screen overlay on top of server-rendered content. Once the model, fonts and images are in and drei's useProgress reports the glTF done, it folds a CSS 3D cube into the WebGL cube's starting pose and fades out. Both cubes read their size from one shared file, and the swap has no visible seam.
People wait for decoration, and on a slow connection that's a real wait. On a portfolio the first impression is close to being the product, so I keep it. I wouldn't put it on a client's shop.
Crawlers skip all of it. A user-agent regex (bot, crawler, spider, headlesschrome and friends) closes the loader instantly and never mounts the scene, and the loader markup has data-nosnippet. Bots still get the same server-rendered content as people. The user-agent check only skips the loader and scene.
Below the fold, the process steps, contact block and footer load only near the viewport. next/dynamic with ssr: false still downloads the chunk right after hydration. The wrapper waits for an IntersectionObserver:
export function DeferredClientSection({ load, props = {}, fallback, rootMargin = "600px 0px" }: Props) {
const hostRef = useRef<HTMLDivElement>(null);
const [Component, setComponent] = useState<React.ComponentType<Record<string, unknown>> | null>(null);
useEffect(() => {
const host = hostRef.current;
if (!host) return;
let cancelled = false;
const observer = new IntersectionObserver(([entry]) => {
if (!entry?.isIntersecting) return;
observer.disconnect();
void load().then((m) => { if (!cancelled) setComponent(() => m.default); });
}, { rootMargin });
observer.observe(host);
return () => { cancelled = true; observer.disconnect(); };
}, [load, rootMargin]);
return <div ref={hostRef}>{Component ? <Component {...props} /> : fallback}</div>;
}
Each fallback is an empty div with a min-height in svh, and the page doesn't jump. These sections aren't in the server HTML, which I'm not sure about for the contact block.
frameloop is still "always"
Even when the cube's callback returns early, R3F renders on every vsync and the camera and lighting callbacks still run. frameloop="demand" plus invalidate() from scroll, hover and the event bus would let an idle page draw nothing. The idle Rubik turns would have to keep invalidating while they run, and that's what's in the way.
More posts
- 01
Deploying Next.js and NestJS to AWS EC2 with Docker Compose
How I deploy a pnpm monorepo to one EC2 box. Images get built in GitHub Actions and Docker Compose pulls them from GHCR. The server has no code.
- 02
How I store OAuth tokens for social media APIs in NestJS
OAuth for Facebook, TikTok and YouTube in a NestJS API. State and PKCE, encrypted tokens, refreshing before each publish, and when to ask for a reconnect.
- 03
llms.txt on my Next.js site, and now Lighthouse grades it
vennee.dev has a hand-written llms.txt and an llms-full.txt built from the blog. Notes on the spec, .txt routes in Next.js, and Lighthouse 13's new audit.