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
- Create a worker file that listens for
messageevents and posts results back. - Instantiate the worker in a component or hook.
- Communicate via
postMessageand clean up in auseEffectreturn 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.