Frontend Blocks typescript Intermediate

Web Worker for Heavy Computation

Offload CPU-intensive work to a Web Worker to keep the UI thread responsive.

typescript
// worker.ts
self.onmessage = (e) => {
  const { data } = e;
  const result = data.reduce((acc: number, n: number) => acc + n, 0);
  self.postMessage({ result });
};

// main.tsx
const worker = new Worker(new URL("./worker.ts", import.meta.url), { type: "module" });

worker.onmessage = (e) => console.log("Sum:", e.data.result);
worker.postMessage(Array.from({ length: 1e6 }, (_, i) => i));

Prerequisites

  • React >= 17
  • Vite or Webpack 5

Pro Tips

  • → Terminate the worker with worker.terminate() when the component unmounts.

Was this module useful?

Share your experience — it helps the team improve.

Leave Feedback

Commercial Licensing

Acquire a production access token or template license for enterprise deployment.

Module Info

Language
typescript
Level
Intermediate
Read time
4 min
Published
Jun 2026
License
Commercial License

Newsletter

New modules every week, directly to your inbox.