How to use Web Workers with React for heavy computations

· Category: React

Short answer

Web Workers run JavaScript in a background thread, keeping the main thread free for UI updates. They are ideal for heavy computations in React apps.

Steps

  1. Create a worker file that listens for message events and posts results back.
  2. Instantiate the worker in a component or hook.
  3. Communicate via postMessage and clean up in a useEffect return function.

Example

// worker.js
self.addEventListener('message', (e) => {
  const result = heavyCalculation(e.data);
  self.postMessage(result);
});
useEffect(() => {
  const worker = new Worker(new URL('./worker.js', import.meta.url));
  worker.postMessage(largeArray);
  worker.onmessage = (e) => setResult(e.data);
  return () => worker.terminate();
}, []);

Tips

  • Workers do not have access to the DOM or React state directly.
  • Use Comlink to simplify the worker API with async/await.
  • For bundler compatibility, use new URL(..., import.meta.url) with Webpack 5 or Vite.