pmndrs / react-three-offscreen

📺 Offscreen worker canvas for react-three-fiber
https://offscreen.pmnd.rs
MIT License
434 stars 14 forks source link

Canvas unmount and mount freezes the scene #16

Closed mhmdjaw closed 2 months ago

mhmdjaw commented 6 months ago

For some reason initializing the worker when the app launches causes freezing issues when the Canvas unmounts and then mounts again. It works fine only on the first mount.

So instead of launching it outside the component where Canvas is rendering I did this:

const CanvasSection = () => {
  // This is the worker thread that will render the scene
  const worker = useMemo(() => new Worker(new URL('./Worker.tsx', import.meta.url), { type: 'module' }), [])

  useEffect(() => () => worker.terminate(), [])

  return <Canvas worker={worker} fallback={<Scene />} />
}

This way I'm initializing the worker whenever the comopnent renders and terminating it when it unmounts. Not sure why the freezing problem was happening but this solved it for me in case someone else runs into it.