All articles
Three.jsReactWebGLPerformance

Fixing Three.js Memory Leaks and WebGL Context Lost in React

Three.js scene in React getting slower on every navigation until the WebGL context is lost? Dispose GPU resources, clean up effects and reuse the renderer.

Tushar Pachouri12 min read

You build a nice vanilla Three.js scene inside a useEffect, drop it on a page in your React or Next.js app, and it runs smoothly. Then you navigate away and back a few times and the frame rate drops, GPU memory keeps climbing, and eventually the console prints WARNING: Too many active WebGL contexts. Oldest context will be lost. followed by THREE.WebGLRenderer: Context Lost. This post explains why it happens and walks through the cleanup code that fixes it.

TL;DR

  • Three.js never frees GPU memory on its own. Removing an object from the scene does not release its geometry, material or textures; you must call dispose() on each of them.
  • Every new THREE.WebGLRenderer() creates a new WebGL context, and browsers only allow a limited number per page (commonly around 16). Leaked renderers push older contexts out.
  • React 18 StrictMode runs effects twice in development, so a useEffect without cleanup creates two renderers, two loops and two scenes on every mount.
  • Write a complete cleanup: cancel the animation loop, remove listeners and observers, dispose the scene tree, dispose the renderer, and remove the canvas.
  • Verify with renderer.info.memory and renderer.info.render, and lazy-load three with dynamic import() so it never ships in your main bundle.

Why the scene leaks

GPU resources are not garbage collected

When you create a BoxGeometry, a MeshStandardMaterial or load a texture, three.js keeps a JavaScript object on the CPU side and uploads buffers, shader programs and texture images to the GPU the first time they render. The JavaScript garbage collector only knows about the JS objects. It has no idea there are vertex buffers and textures sitting in video memory.

CPU: JAVASCRIPT HEAP GPU: VIDEO MEMORY BoxGeometry vertex buffers MeshStandardMaterial shader program Texture texture image freed by garbage collection GC cannot see these: call dispose()
The garbage collector frees the JavaScript objects but never the GPU copies they uploaded.

So scene.remove(mesh) or simply letting the component unmount does nothing for GPU memory. The three.js docs are explicit about this: geometries, materials, textures and render targets each need an explicit dispose() call.

Each renderer is a WebGL context

new THREE.WebGLRenderer() calls canvas.getContext('webgl2') under the hood. Contexts are expensive, and browsers cap how many can be alive at once. When you exceed the cap, the browser forcibly kills the oldest one, which is where the "Too many active WebGL contexts" warning comes from. If that oldest context belongs to the scene the user is currently looking at, it goes blank.

Every leaked renderer holds a context until the browser's cap pushes the oldest one out.

A context is only released when the canvas and renderer are garbage collected, which can take a long time, or when you explicitly force it to be lost.

StrictMode doubles everything

In development, React 18 StrictMode mounts your component, runs the cleanup, and mounts it again to surface missing cleanups. If your effect has no cleanup, you get two canvases, two renderers and two requestAnimationFrame loops on every page visit. Navigate back and forth five times and you have ten loops rendering into detached canvases.

Here is the kind of effect that causes all of this:

TSX
// Broken: no cleanup at all
useEffect(() => {
  const renderer = new THREE.WebGLRenderer({ antialias: true });
  containerRef.current!.appendChild(renderer.domElement);

  const scene = new THREE.Scene();
  const camera = new THREE.PerspectiveCamera(50, 1, 0.1, 100);
  const mesh = new THREE.Mesh(
    new THREE.BoxGeometry(1, 1, 1),
    new THREE.MeshStandardMaterial({ map: new THREE.TextureLoader().load('/textures/crate.jpg') })
  );
  scene.add(mesh);

  function animate() {
    requestAnimationFrame(animate); // never cancelled
    renderer.render(scene, camera);
  }
  animate();

  window.addEventListener('resize', () => {
    renderer.setSize(window.innerWidth, window.innerHeight); // never removed
  });
}, []);

Every mount leaks a context, a loop that keeps the scene alive forever (because the closure references it), a texture, a geometry, a material and a resize listener.

A robust dispose helper

Before fixing the effect, we need a way to free everything inside a scene. The helper below traverses the tree, disposes geometry and every material, and disposes every texture found on those materials, including textures inside ShaderMaterial uniforms. It tracks what it has already disposed so shared resources are handled once.

TypeScript
// lib/three/dispose.ts
import * as THREE from 'three';

type Disposable = { dispose: () => void };

function isTexture(value: unknown): value is THREE.Texture {
  // Duck-type instead of instanceof, so it still works if two copies of three get bundled
  return !!value && (value as THREE.Texture).isTexture === true;
}

function disposeTexturesIn(source: Record<string, unknown>, seen: Set<Disposable>) {
  for (const value of Object.values(source)) {
    if (isTexture(value) && !seen.has(value)) {
      seen.add(value);
      value.dispose();
    }
  }
}

function disposeMaterial(material: THREE.Material, seen: Set<Disposable>) {
  if (seen.has(material)) return;
  seen.add(material);

  // map, normalMap, roughnessMap, envMap, alphaMap, and so on
  disposeTexturesIn(material as unknown as Record<string, unknown>, seen);

  // Textures passed as uniforms to ShaderMaterial / RawShaderMaterial
  const uniforms = (material as THREE.ShaderMaterial).uniforms;
  if (uniforms) {
    for (const uniform of Object.values(uniforms)) {
      const value = uniform?.value;
      if (isTexture(value) && !seen.has(value)) {
        seen.add(value);
        value.dispose();
      } else if (Array.isArray(value)) {
        value.forEach((item) => {
          if (isTexture(item) && !seen.has(item)) {
            seen.add(item);
            item.dispose();
          }
        });
      }
    }
  }

  material.dispose();
}

export function disposeTree(root: THREE.Object3D) {
  const seen = new Set<Disposable>();

  root.traverse((object) => {
    const renderable = object as THREE.Mesh | THREE.Points | THREE.Line;
    const isRenderable =
      (renderable as THREE.Mesh).isMesh ||
      (renderable as THREE.Points).isPoints ||
      (renderable as THREE.Line).isLine;

    if (!isRenderable) return;

    if (renderable.geometry && !seen.has(renderable.geometry)) {
      seen.add(renderable.geometry);
      renderable.geometry.dispose();
    }

    const materials = Array.isArray(renderable.material)
      ? renderable.material
      : [renderable.material];
    materials.forEach((material) => material && disposeMaterial(material, seen));

    // SkinnedMesh skeletons own a bone texture
    const skinned = object as THREE.SkinnedMesh;
    if (skinned.isSkinnedMesh && skinned.skeleton) skinned.skeleton.dispose();

    // InstancedMesh has its own dispose
    const instanced = object as THREE.InstancedMesh;
    if (instanced.isInstancedMesh) instanced.dispose();
  });

  const scene = root as THREE.Scene;
  if (scene.isScene) {
    if (isTexture(scene.background)) scene.background.dispose();
    if (isTexture(scene.environment)) scene.environment.dispose();
  }
}

Warning: Only dispose resources you own. If a texture or material is shared with a scene that is still on screen, three.js will re-upload it on next use, which causes a stutter. If the texture's image was an ImageBitmap you already closed, it will not come back at all.

The fixed useEffect

Now the component. Every resource created in setup has a matching line in cleanup, in reverse order.

Each resource the effect creates has a matching line in its cleanup function.
TSX
'use client';

import { useEffect, useRef } from 'react';
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
import { disposeTree } from '@/lib/three/dispose';

export default function Scene() {
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const container = containerRef.current;
    if (!container) return;

    // Setup
    const renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
    renderer.setSize(container.clientWidth, container.clientHeight);
    container.appendChild(renderer.domElement);

    const scene = new THREE.Scene();
    const camera = new THREE.PerspectiveCamera(
      50,
      container.clientWidth / container.clientHeight,
      0.1,
      100
    );
    camera.position.set(0, 0, 4);

    const texture = new THREE.TextureLoader().load('/textures/crate.jpg');
    const mesh = new THREE.Mesh(
      new THREE.BoxGeometry(1, 1, 1),
      new THREE.MeshStandardMaterial({ map: texture })
    );
    const light = new THREE.DirectionalLight(0xffffff, 2);
    light.position.set(2, 3, 4);
    scene.add(mesh, light, new THREE.AmbientLight(0xffffff, 0.4));

    const controls = new OrbitControls(camera, renderer.domElement);

    // Animation loop
    let frameId = 0;
    const tick = () => {
      mesh.rotation.y += 0.01;
      controls.update();
      renderer.render(scene, camera);
      frameId = requestAnimationFrame(tick);
    };
    frameId = requestAnimationFrame(tick);

    // Resize with the container, not just the window
    const resizeObserver = new ResizeObserver(() => {
      const { clientWidth, clientHeight } = container;
      if (!clientWidth || !clientHeight) return;
      camera.aspect = clientWidth / clientHeight;
      camera.updateProjectionMatrix();
      renderer.setSize(clientWidth, clientHeight);
    });
    resizeObserver.observe(container);

    const onVisibility = () => {
      cancelAnimationFrame(frameId);
      if (!document.hidden) frameId = requestAnimationFrame(tick);
    };
    document.addEventListener('visibilitychange', onVisibility);

    // Cleanup
    return () => {
      cancelAnimationFrame(frameId);
      document.removeEventListener('visibilitychange', onVisibility);
      resizeObserver.disconnect();
      controls.dispose();

      disposeTree(scene);
      scene.clear();

      renderer.dispose();
      renderer.forceContextLoss();
      renderer.domElement.remove();
    };
  }, []);

  return <div ref={containerRef} style={{ width: '100%', height: '100%' }} />;
}

A few details that matter:

  • controls.dispose() removes the pointer and wheel listeners OrbitControls attached to the canvas. Most of the addons in three/examples/jsm have a dispose() method; call it.
  • renderer.dispose() frees the renderer's internal caches, but it does not dispose your scene's geometries, materials or textures. That is why disposeTree runs first.
  • renderer.forceContextLoss() uses the WEBGL_lose_context extension to release the context immediately instead of waiting for garbage collection. Use it when this renderer is truly done, as it is here because a new one is created on the next mount.
  • If you use renderer.setAnimationLoop(tick) instead of requestAnimationFrame, the cleanup is renderer.setAnimationLoop(null).

Note: forceContextLoss() fires a webglcontextlost event, so you will see THREE.WebGLRenderer: Context Lost. logged during cleanup. That one is expected. The one to worry about is when it appears while the scene is on screen.

Reuse one renderer across routes

If a 3D scene appears on several routes, or a user navigates back and forth often, creating a renderer per mount is wasteful even with perfect cleanup. A better pattern is a single renderer that you move between containers.

TypeScript
// lib/three/renderer.ts
import * as THREE from 'three';

let shared: THREE.WebGLRenderer | null = null;

export function getSharedRenderer() {
  if (!shared) {
    shared = new THREE.WebGLRenderer({ antialias: true, alpha: true });
    shared.setPixelRatio(Math.min(window.devicePixelRatio, 2));
  }
  return shared;
}
TSX
useEffect(() => {
  const container = containerRef.current;
  if (!container) return;

  const renderer = getSharedRenderer();
  renderer.setSize(container.clientWidth, container.clientHeight);
  container.appendChild(renderer.domElement);

  const scene = new THREE.Scene();
  const camera = new THREE.PerspectiveCamera(50, container.clientWidth / container.clientHeight, 0.1, 100);
  // build the scene for this route here

  renderer.setAnimationLoop(() => renderer.render(scene, camera));

  return () => {
    renderer.setAnimationLoop(null);
    disposeTree(scene);
    scene.clear();
    renderer.domElement.remove(); // detach, but keep the renderer and its context
  };
}, []);

The scene's resources are still disposed per route, but the context lives for the life of the app. You can never hit the context limit this way, and renderer.info becomes a reliable leak detector because its counters persist across navigations.

shared WebGLRenderer one context for the life of the app CANVAS MOVES Route A container own Scene and camera on leave: disposeTree(scene) canvas detached, renderer kept Route B container own Scene and camera on leave: disposeTree(scene) canvas detached, renderer kept
One renderer and one context move between routes, while each route disposes its own scene.

Textures, canvases and render targets

Loaded textures

Textures from TextureLoader are only freed when you call texture.dispose(). If you assign them to a material, disposeTree catches them. If you keep them somewhere else, such as a cache map or a uniform you swap at runtime, dispose them yourself when you replace or drop them.

TypeScript
const loader = new THREE.TextureLoader();
let current = loader.load('/textures/day.jpg');
material.map = current;

function swapTo(url: string) {
  const next = loader.load(url);
  material.map = next;
  material.needsUpdate = true;
  current.dispose(); // the old texture is still on the GPU otherwise
  current = next;
}

If you use ImageBitmapLoader, also call texture.image.close() after disposing to free the decoded bitmap on the CPU side.

CanvasTexture

A common leak is creating a fresh CanvasTexture every time a label or chart changes. Create one, redraw the 2D canvas, and flag it for re-upload:

Diff
- function updateLabel(text: string) {
-   drawText(ctx, text);
-   sprite.material.map = new THREE.CanvasTexture(canvas); // new GPU texture every call
- }
+ const labelTexture = new THREE.CanvasTexture(canvas);
+ sprite.material.map = labelTexture;
+
+ function updateLabel(text: string) {
+   drawText(ctx, text);
+   labelTexture.needsUpdate = true; // re-uploads into the same texture
+ }

Render targets and EffectComposer

Every WebGLRenderTarget owns a texture and framebuffer, and postprocessing pipelines create several. Dispose them explicitly:

TypeScript
import { EffectComposer } from 'three/examples/jsm/postprocessing/EffectComposer.js';
import { RenderPass } from 'three/examples/jsm/postprocessing/RenderPass.js';
import { UnrealBloomPass } from 'three/examples/jsm/postprocessing/UnrealBloomPass.js';

const composer = new EffectComposer(renderer);
composer.addPass(new RenderPass(scene, camera));
composer.addPass(new UnrealBloomPass(new THREE.Vector2(width, height), 0.8, 0.4, 0.85));

const pickingTarget = new THREE.WebGLRenderTarget(width, height);

// In cleanup
for (const pass of composer.passes) pass.dispose();
composer.dispose(); // frees the composer's internal render targets
pickingTarget.dispose();

Tip: If you are on an older three.js where EffectComposer has no dispose(), call composer.renderTarget1.dispose() and composer.renderTarget2.dispose() instead.

Handling context loss gracefully

Even with perfect cleanup, a context can be lost for reasons outside your control: a GPU driver reset, the OS reclaiming memory, or another tab hogging contexts. Handle the events instead of leaving a frozen black canvas.

TypeScript
const canvas = renderer.domElement;

const onContextLost = (event: Event) => {
  event.preventDefault(); // signals that we want the context restored
  cancelAnimationFrame(frameId);
  setStatus('lost'); // show a fallback or a retry message
};

const onContextRestored = () => {
  setStatus('ok');
  frameId = requestAnimationFrame(tick);
};

canvas.addEventListener('webglcontextlost', onContextLost);
canvas.addEventListener('webglcontextrestored', onContextRestored);

// In cleanup, remove these BEFORE forceContextLoss()
// so your own teardown does not trigger the fallback UI
canvas.removeEventListener('webglcontextlost', onContextLost);
canvas.removeEventListener('webglcontextrestored', onContextRestored);

Three.js itself already calls preventDefault() on context loss and reinitialises its internal state when the context comes back, re-uploading geometries and textures on the next render as long as their CPU-side data still exists. Your job is to stop the loop, show the user something sensible, and restart rendering on restore.

Verify the fix with renderer.info

Do not guess whether the leak is gone; measure it. renderer.info.memory counts geometries and textures currently on the GPU, and renderer.info.render reports draw calls and triangles for the last frame.

TypeScript
if (process.env.NODE_ENV === 'development') {
  const logId = window.setInterval(() => {
    const { memory, render, programs } = renderer.info;
    console.table({
      geometries: memory.geometries,
      textures: memory.textures,
      programs: programs?.length ?? 0,
      drawCalls: render.calls,
      triangles: render.triangles,
    });
  }, 2000);
  // remember to clearInterval(logId) in cleanup
}

With the shared-renderer pattern, navigate away and back several times. The numbers should return to the same baseline each time. If textures climbs by a fixed amount per visit, something is not being disposed.

With a renderer per mount, the counters reset with each new renderer, so log renderer.info.memory right after disposeTree(scene) in cleanup instead. It should drop to zero, or to whatever you intentionally keep alive. Also run document.querySelectorAll('canvas').length in the console after a few navigations, and watch the GPU memory column in Chrome's Task Manager.

What about React Three Fiber?

React Three Fiber disposes objects it creates declaratively when they unmount: a <mesh> with a <boxGeometry> and <meshStandardMaterial> is cleaned up for you, and the <Canvas> disposes its renderer.

It does not know about anything you create imperatively, such as new THREE.Texture() in a useMemo, a render target in a ref, or an EffectComposer you wire up by hand. Those still need a useEffect cleanup that calls dispose().

Assets loaded through useLoader or useGLTF are cached and shared between components. If two components render the same cached model, letting one of them dispose it on unmount breaks the other. Use dispose={null} on the primitive to opt out of automatic disposal:

TSX
function Model() {
  const { scene } = useGLTF('/models/robot.glb');
  // The cached scene is shared, so do not let R3F dispose it on unmount
  return <primitive object={scene} dispose={null} />;
}

Use it deliberately, though. dispose={null} on something that is not shared just turns it back into a leak.

Keep three out of the main bundle

three is a large dependency. If only one page uses it, it should not be in every page's JavaScript. In Next.js, load the scene component with next/dynamic and skip server rendering, since WebGL needs a browser anyway:

TSX
// components/SceneLoader.tsx
'use client';

import dynamic from 'next/dynamic';

const Scene = dynamic(() => import('./Scene'), {
  ssr: false,
  loading: () => <div className="h-full w-full animate-pulse bg-neutral-900" />,
});

export default function SceneLoader() {
  return <Scene />;
}

If you prefer to keep the component itself light, move the setup into a plain module that returns its own cleanup function, and import it inside the effect. Watch for the race where the component unmounts before the import resolves:

TSX
useEffect(() => {
  let cancelled = false;
  let cleanup: (() => void) | undefined;

  import('@/lib/three/createScene').then(({ createScene }) => {
    if (cancelled || !containerRef.current) return;
    cleanup = createScene(containerRef.current); // returns the teardown function
  });

  return () => {
    cancelled = true;
    cleanup?.();
  };
}, []);

Without the cancelled flag, StrictMode's mount-unmount-mount sequence can run cleanup before setup has happened, and the first scene is never torn down.

Checklist

  • Every useEffect that creates a renderer, scene or loop returns a cleanup function.
  • cancelAnimationFrame or renderer.setAnimationLoop(null) runs on unmount.
  • Window and document listeners are removed, and ResizeObserver is disconnected.
  • Addons like OrbitControls have dispose() called.
  • disposeTree(scene) frees every geometry, material and material texture, including uniforms, scene.background and scene.environment.
  • Swapped textures and CanvasTexture are reused or disposed, never recreated silently.
  • Render targets, composer passes and the composer are disposed.
  • renderer.dispose() runs, plus forceContextLoss() if the renderer will not be reused.
  • A single shared renderer is used when the scene appears on multiple routes.
  • webglcontextlost and webglcontextrestored are handled with a fallback UI.
  • renderer.info.memory returns to the same baseline after navigating away and back.
  • three is loaded with dynamic import() and stays out of the main bundle.

Stuck on something like this?

I build and fix full-stack products for startups and indie founders. Tell me what's broken.

Get in touch