Performance issues ThreeJS & ReactJS

I’m having some performances issues with ThreeJS & ReactJS. I’m having different pages with ThreeJS scenes. I’m using useEffect and on the callback function, I remove the children of the scene.

This is my callback function:

    return () => {
      window.removeEventListener("resize", handleResize);
      mount.current.removeChild(renderer.domElement);
      scene.remove(scene.children[0]);
    };

However when I’m using the site for a while. It gets slower and slower. I’m also using mtl and object loaders to load some objects. Is there a better way in cleaning the scene and get better performance?

Just removing objects from the scene graph is not enough to free all allocated resources. You also have to call dispose() on all geometries, materials and textures in your scene. You can read more about this topic here:

https://threejs.org/docs/index.html#manual/en/introduction/How-to-dispose-of-objects

Notice that if you are not free resources correctly, you will run into a memory leak.

Thanks for the info! I followed the docs and removed all the geometries and materials. It runs a lot better now!

There is 1 thing that is still not clear for me. After I change pages for like 10-15 times, I get this message in the console.

Too many active WebGL contexts. Oldest context will be lost.

How can I prevent this from happening?

you should not bring down the whole canvas but let it stand and exchange its contents, you are putting way too much stress on the GC, not to mention the overhead of three having to chomp through shaders and geometries again - also like @Mugen87 said, simply removing items will leave gaping memory leaks.

since you are using react, use react-three-fiber. it takes care of all of these little problems like auto-disposal - just like react-dom does with divs and spans. it also seamlessly ties into your app, for instance it will receive your routes. if you use plain three you have to constantly bridge two worlds that have nothing whatsoever to do with one another and that becomes hard to manage.

here’s a more involved example for routes, transitions and exchanging contents: https://codesandbox.io/s/7kohn couldn’t find a simpler one but in essence - it is the same exact way you manage your dom content.