How should I handle WebGL context when switching to a new page?

On my personal website, I’m using Next.js with static pages and have set up a DOM and canvas on the homepage. When I switch to another page away from the canvas, I get the warning THREE.WebGLRenderer: Context Lost.

Everything runs fine in real world usage, but I’m wondering if there’s a better way to handle switching to and from the page with the canvas on it.

you should simply not do that, unmounting canvas on route change eventually will crash the tab because you can only open a limited amount of canvases and it’s going to cause memory issues, jank and slowness. instead leave the canvas mounted and exchange contents. with ssr and ssg websites should feel instant, that is established by switching components instead of refreshing the whole page and the same applies to the canvas.

here’s an example of how fast threejs can be in a nextjs routing context: GitHub - pmndrs/react-three-next: React Three Fiber, Nextjs, Tailwind and Styled-components starter

1 Like

It’s difficult to say without seeing your implementation, a link to a live example of your setup would help debug, are you using componentWillUnmount() for instance? There doesn’t seem the need to destroy your webgl context if the site is dynamic and is never actually reloaded

Ahh ok. My site just has a canvas on the front page for a fun visual, but the rest of the site is just basic text and images. I was following that NextJS template, but it seemed more focused on bouncing between canvases.

I haven’t looked into unmounting at all. Everything sort of just works, so I hadn’t thought about mounting and unmounting the context until now. I’m simply navigating away entirely to a new dynamic page and losing the context.