Web Workers to run task in background
Watch the walkthrough
Open on InstagramQuick revision
A dedicated Web Worker runs JavaScript in another execution context. It can move a CPU-heavy calculation off the main thread so input and rendering can continue. It cannot access the page's DOM directly. postMessage communicates using structured cloning, or transferables for supported objects.
Read the copied example
HeavyComponent.tsx performs its calculation during render and blocks the main thread. HeavyComponent2.tsx starts a worker in an Effect, posts a request, and stores the result received through onmessage. worker.js performs the same calculation and replies. Cleanup terminates the worker; termination also happens after its one result arrives.
The example uses Vite's worker URL pattern. It needs the worker file alongside the component and the project's bundler configuration. It has no worker error handling or request IDs; add those if the work can fail or multiple jobs overlap. A worker has startup and messaging costs, so small calculations may not benefit.
Revision checks
Compare a performance trace with the main-thread version. Interact with a light counter during the calculation, then unmount the worker component and confirm the job stops. Keeping the calculation in async/await would not move CPU work off the thread.
Reference: Using Web Workers. Related theory: Browser performance revision.
Original repository source
These are the supplied checkout's React 18/Vite examples. Code is preserved apart from line endings; revision recommendations above are separate. Use the original project dependencies and configuration when running them.
HeavyComponent.tsx
const HeavyComponent = () => {
const expensiveCalculation = () => {
let result = 0;
// for loop: 100 million times
for (let i = 0; i < 100000000; i++) {
result += Math.sin(i) * Math.cos(i);
}
return result;
};
const computationResult = expensiveCalculation();
return (
<div className="p-6 bg-orange-100 rounded-lg">
<h2 className="text-2xl font-bold mb-4">Heavy Component 1</h2>
<p className="text-sm text-gray-600 my-2">
This component took significant time to render due to heavy
computational work {computationResult}
</p>
<img className="rounded-md" src="her_1.png" alt="her_1" />
</div>
);
};
export default HeavyComponent;
HeavyComponent2.tsx
import React, { useState, useEffect } from "react";
const HeavyComponent2 = () => {
const [computationResult, setComputationResult] = useState<number | null>(
null
);
useEffect(() => {
const worker = new Worker(new URL("./worker.js", import.meta.url));
worker.postMessage({ type: "expensiveCalculation" });
worker.onmessage = (e) => {
setComputationResult(e.data);
worker.terminate();
};
return () => worker.terminate();
}, []);
return (
<div className="p-6 bg-orange-100 rounded-lg">
<h2 className="text-2xl font-bold mb-4">Heavy Component 2</h2>
{computationResult === null ? (
<p className="text-sm text-gray-600 my-2">Loading...</p>
) : (
<>
<p className="text-sm text-gray-600 my-2">
This component took significant time to render due to heavy
computational work. Computation Result: {computationResult}
</p>
<img className="rounded-md" src="her_1.png" alt="her_1" />
</>
)}
</div>
);
};
export default HeavyComponent2;
worker.js
self.onmessage = (e) => {
const { type, payload } = e.data;
if (type === "expensiveCalculation") {
let result = 0;
for (let i = 0; i < 100000000; i++) {
result += Math.sin(i) * Math.cos(i);
}
postMessage(result); // Send the result back to the main thread
}
};