Lesson 8 of 10
Web Workers - Offloading Heavy Computation
JavaScript is single-threaded - heavy CPU work (sorting large datasets, parsing CSVs, image processing, cryptography) blocks the main thread, freezing the UI. Web Workers run in a separate thread. React receives the result without ever blocking the UI.
Web Worker Basics & Comlink
// ---- The problem: main-thread blocking ----
function sortHugeDataset(data: Row[]) {
// This while-loop blocks the main thread → UI freezes for seconds
return data.sort((a, b) => complexComparison(a, b));
}
// ---- Solution: Web Worker via Comlink ----
// Comlink is a tiny library that wraps the postMessage API with Promises
// worker.ts - runs in a separate thread, no DOM access
import * as Comlink from 'comlink';
const api = {
// sortRows runs off the main thread - UI stays responsive
sortRows(data: Row[], column: string, direction: 'asc' | 'desc'): Row[] {
return [...data].sort((a, b) => {
const valA = a[column];
const valB = b[column];
const cmp = typeof valA === 'string'
? valA.localeCompare(valB as string)
: (valA as number) - (valB as number);
return direction === 'asc' ? cmp : -cmp;
});
},
parseCSV(csvText: string): Record<string, string>[] {
const lines = csvText.split('\n');
const headers = lines[0].split(',');
return lines.slice(1).map(line => {
const values = line.split(',');
return Object.fromEntries(headers.map((h, i) => [h.trim(), values[i]?.trim() ?? '']));
});
},
// Long-running with progress reporting
processData(data: number[], onProgress: Comlink.Remote<(pct: number) => void>): number[] {
const result: number[] = [];
for (let i = 0; i < data.length; i++) {
result.push(data[i] * 2); // expensive operation
if (i % 1000 === 0) onProgress(Math.round((i / data.length) * 100));
}
return result;
},
};
Comlink.expose(api);
export type WorkerAPI = typeof api;
// ---- useWorker hook - wraps worker lifecycle in React ----
import { useEffect, useRef, useCallback } from 'react';
import * as Comlink from 'comlink';
import type { WorkerAPI } from './worker';
function useDataWorker() {
const workerRef = useRef<Worker | null>(null);
const apiRef = useRef<Comlink.Remote<WorkerAPI> | null>(null);
useEffect(() => {
// new URL() + import.meta.url tells Vite to bundle this as a worker chunk
workerRef.current = new Worker(new URL('./worker.ts', import.meta.url), { type: 'module' });
apiRef.current = Comlink.wrap<WorkerAPI>(workerRef.current);
return () => {
workerRef.current?.terminate(); // always terminate on unmount
};
}, []);
const sortRows = useCallback(async (data: Row[], column: string, direction: 'asc' | 'desc') => {
if (!apiRef.current) throw new Error('Worker not ready');
return apiRef.current.sortRows(data, column, direction);
}, []);
const parseCSV = useCallback(async (csv: string) => {
if (!apiRef.current) throw new Error('Worker not ready');
return apiRef.current.parseCSV(csv);
}, []);
return { sortRows, parseCSV };
}
// ---- Using the hook in a component ----
function DataTable({ rawData }: { rawData: Row[] }) {
const [sortedData, setSortedData] = useState<Row[]>(rawData);
const [sorting, setSorting] = useState(false);
const [sortCol, setSortCol] = useState<string | null>(null);
const { sortRows } = useDataWorker();
async function handleColumnSort(column: string) {
setSorting(true);
try {
// Main thread is FREE during sort - UI stays interactive
const sorted = await sortRows(rawData, column, 'asc');
setSortedData(sorted);
setSortCol(column);
} finally {
setSorting(false);
}
}
return (
<div>
{sorting && <div style={{ opacity: 0.5 }}>Sorting...</div>}
<table>
<thead>
<tr>
{Object.keys(rawData[0] ?? {}).map(col => (
<th key={col} onClick={() => handleColumnSort(col)} style={{ cursor: 'pointer' }}>
{col} {sortCol === col ? '↑' : ''}
</th>
))}
</tr>
</thead>
<tbody>
{sortedData.slice(0, 100).map((row, i) => (
<tr key={i}>{Object.values(row).map((v, j) => <td key={j}>{String(v)}</td>)}</tr>
))}
</tbody>
</table>
</div>
);
}Common Mistakes - Web Workers
- Accessing the DOM in a worker - workers can't access `document`, `window`, or any DOM API; put all DOM work in the main thread, pass data back via postMessage
- Not terminating workers on unmount - each `new Worker()` creates an OS thread; failing to call `worker.terminate()` in useEffect cleanup leaks threads
- Passing non-transferable data - complex objects are deep-cloned (slow) when sent to a worker; use Transferable objects (ArrayBuffer, ImageBitmap) for large data via `postMessage(data, [data.buffer])`
- Using Comlink without bundler worker support - Vite's `new URL('./worker.ts', import.meta.url)` pattern is required; without it the worker file isn't bundled correctly
- Worrying about simple operations - a sort of 1,000 items runs in under 1ms on the main thread; only move to a worker if a task takes >50ms and noticeably jank the UI
Tip
Tip
Practice Web Workers Offloading Heavy Computation in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and flow for Web Workers - Offloading Heavy Computation
Practice Task
Note
Practice Task - (1) Write a working example of Web Workers Offloading Heavy Computation from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Web Workers Offloading Heavy Computation is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.
Key Takeaways
- JavaScript is single-threaded - heavy CPU work (sorting large datasets, parsing CSVs, image processing, cryptography) blocks the main thread, freezing the UI.
- Accessing the DOM in a worker - workers can't access `document`, `window`, or any DOM API; put all DOM work in the main thread, pass data back via postMessage
- Not terminating workers on unmount - each `new Worker()` creates an OS thread; failing to call `worker.terminate()` in useEffect cleanup leaks threads
- Passing non-transferable data - complex objects are deep-cloned (slow) when sent to a worker; use Transferable objects (ArrayBuffer, ImageBitmap) for large data via `postMessage(data, [data.buffer])`
Finished this lesson?