Imagine building a dashboard that lets users explore a large collection of sales records. They can change the date range, filter by region and compare revenue across product categories.
Everything works well with a few hundred records. Then a customer imports a much larger dataset. Changing a filter makes the interface hesitate. Typing becomes uncomfortable. A loading indicator appears later than expected, even though no network request is involved.
You inspect the component and find an expensive calculation. Naturally, you reach for useMemo.
const summary = useMemo(
() => summariseSales(records, region),
[records, region]
);
The dashboard improves when unrelated state changes. But changing the region still makes the page freeze.
The optimisation isn't necessarily wrong. It is solving a different problem.
1. Memoisation avoids work. It doesn't move work elsewhere.
Consider a function that calculates revenue by category for a selected region. The records contain integer amounts in cents, and the example assumes totals remain within JavaScript's safe integer range.
// summarise-sales.js
export function summariseSales(records, region) {
const totals = new Map();
for (const record of records) {
if (region !== "all" && record.region !== region) {
continue;
}
const previous = totals.get(record.category) ?? 0;
totals.set(record.category, previous + record.amountCents);
}
return Array.from(totals, ([category, amountCents]) => ({
category,
amountCents
})).sort((a, b) => b.amountCents - a.amountCents);
}
This is deliberately ordinary JavaScript. It scans records, aggregates values and sorts the resulting categories. The runtime depends on the number of records, category count, device and data representation. It may be perfectly fast for your application; profile it before moving it to a worker.
In React, we could write:
function SalesReport({ records, region }) {
const summary = useMemo(
() => summariseSales(records, region),
[records, region]
);
return <RevenueTable rows={summary} />;
}
React can reuse the previous calculation when the dependencies remain equal according to Object.is. It doesn't need to scan the records again simply because some unrelated part of the component renders.
But when region changes, the calculation must run again. It runs synchronously as part of rendering, on the browser's main thread in a typical client-rendered React application.
That is the same thread that handles input events, runs application JavaScript and performs much of the work needed to update the page.
Suppose one calculation takes 120 milliseconds. Even if memoisation removes nine out of ten calculations, the remaining calculation can still occupy the main thread for 120 milliseconds. At 60 Hz, that is roughly seven frame intervals, although actual missed frames depend on timing and browser scheduling.
SVG source
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 760 375" width="760" height="375" role="img" aria-label="Comparison of a blocking calculation and a separate worker lane">
<rect x="0" y="0" width="760" height="375" rx="6" fill="#f6f4ee" stroke="none"/>
<text x="24" y="34" font-family="Arial, sans-serif" font-size="20" text-anchor="start" fill="#242b25">Avoiding work vs moving work</text>
<text x="24" y="66" font-family="Arial, sans-serif" font-size="14" text-anchor="start" fill="#6d7268">Main thread with memoisation</text><rect x="24" y="82" width="160" height="45" rx="6" fill="#e6eadd" stroke="#d9ddd2"/><text x="104.0" y="109.5" font-family="Arial, sans-serif" font-size="14" text-anchor="middle" fill="#242b25">Input</text><rect x="194" y="82" width="350" height="45" rx="6" fill="#fffef9" stroke="#ab4932"/><text x="369.0" y="109.5" font-family="Arial, sans-serif" font-size="14" text-anchor="middle" fill="#242b25">Required calculation</text><rect x="554" y="82" width="182" height="45" rx="6" fill="#e6eadd" stroke="#d9ddd2"/><text x="645.0" y="109.5" font-family="Arial, sans-serif" font-size="14" text-anchor="middle" fill="#242b25">UI can respond</text><text x="369" y="148" font-family="Arial, sans-serif" font-size="14" text-anchor="middle" fill="#ab4932">Main thread occupied during calculation</text><line x1="24" y1="166" x2="736" y2="166" stroke="#d9ddd2" stroke-width="1.5"/><text x="24" y="193" font-family="Arial, sans-serif" font-size="14" text-anchor="start" fill="#6d7268">Main thread with worker</text><rect x="24" y="208" width="160" height="40" rx="6" fill="#e6eadd" stroke="#d9ddd2"/><text x="104.0" y="233.0" font-family="Arial, sans-serif" font-size="14" text-anchor="middle" fill="#242b25">Input</text><rect x="194" y="208" width="542" height="40" rx="6" fill="#e6eadd" stroke="#d9ddd2"/><text x="465.0" y="233.0" font-family="Arial, sans-serif" font-size="14" text-anchor="middle" fill="#242b25">UI remains available</text><text x="24" y="273" font-family="Arial, sans-serif" font-size="14" text-anchor="start" fill="#6d7268">Worker thread</text><rect x="194" y="287" width="350" height="40" rx="6" fill="#fffef9" stroke="#242b25"/><text x="369.0" y="312.0" font-family="Arial, sans-serif" font-size="14" text-anchor="middle" fill="#242b25">Required calculation</text><text x="24" y="354" font-family="Arial, sans-serif" font-size="12" text-anchor="start" fill="#6d7268">Conceptual timelines; actual scheduling and durations vary.</text>
</svg>Memoisation reduces the frequency of calculations. A worker changes where those calculations execute.
A useful way to think about it is to separate two questions: how often must this work happen, and where should it happen when it does?
React's useMemo documentation describes memoisation as a performance optimisation rather than a semantic guarantee. React Compiler can also automate some memoisation, but it does not automatically relocate arbitrary JavaScript calculations to a Web Worker.
2. An asynchronous function is not necessarily non-blocking
Perhaps we can solve this by making the function asynchronous.
async function calculateReport(records, region) {
return summariseSales(records, region);
}
Unfortunately, the expensive function still runs synchronously on the thread that calls it. Declaring the function async changes how its result is returned, not where its computation executes.
The same problem exists here:
Promise.resolve().then(() => {
return summariseSales(records, region);
});
The calculation runs in a microtask. It has not been moved to a background thread. A long microtask can still delay input and rendering.
Even setTimeout isn't a complete solution:
setTimeout(() => {
const result = summariseSales(records, region);
showResult(result);
}, 0);
Scheduling the calculation for a later task may give other work an opportunity to run first, but once the callback starts, it can still occupy the main thread until it finishes.
There is a legitimate alternative: split a large computation into small chunks and yield between them. That can work well when the algorithm naturally supports incremental processing. It also avoids copying data between threads.
But it requires the calculation to cooperate with the scheduler. A large synchronous library call cannot be made interruptible just by placing it inside a promise.
The distinction also applies to React's useDeferredValue and useTransition. They help React prioritise rendering. They do not turn an arbitrary synchronous function into interruptible background computation. React cannot yield in the middle of your ordinary JavaScript loop merely because it was started in a transition.
3. Move the calculation to a dedicated Web Worker
A dedicated worker runs JavaScript in a separate worker context. It can perform calculations without directly occupying the page's main thread. It cannot directly manipulate the DOM; it exchanges messages with the application instead.
Let's reuse our existing aggregation function rather than invent a different algorithm.
// sales.worker.js
import { summariseSales } from "./summarise-sales.js";
let records = [];
self.addEventListener("message", ({ data }) => {
const { type, id, region } = data;
try {
if (type === "init") {
records = data.records;
return;
}
if (type === "calculate") {
const rows = summariseSales(records, region);
self.postMessage({ type: "result", id, rows });
}
} catch (error) {
self.postMessage({
type: "error",
id,
message: error instanceof Error
? error.message
: String(error)
});
}
});
The worker keeps the dataset in its own memory. Instead of sending every sales record again when the region changes, we send a small message containing the region and a request identifier.
The application creates the worker:
const worker = new Worker(
new URL("./sales.worker.js", import.meta.url),
{ type: "module" }
);
worker.addEventListener("message", ({ data }) => {
console.log(data);
});
worker.postMessage({ type: "init", records });
worker.postMessage({
type: "calculate",
id: 1,
region: "Asia"
});
This example uses the module-worker URL pattern supported by bundlers such as Vite. Check the build tooling and deployment's Content Security Policy when integrating it into an existing application.
Messages sent by the same sender through this worker connection are processed in order, so the synchronous initialization handler runs before the calculation handler.
While the worker computes the totals, the main thread can continue responding to the user, subject to available CPU resources and other work happening on the device.
SVG source
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 760 266" width="760" height="266" role="img" aria-label="Initial data stored in a worker and later filter messages producing small summaries">
<rect x="0" y="0" width="760" height="266" rx="6" fill="#f6f4ee" stroke="none"/>
<text x="24" y="34" font-family="Arial, sans-serif" font-size="20" text-anchor="start" fill="#242b25">A persistent worker keeps the dataset</text>
<rect x="24" y="70" width="160" height="52" rx="6" fill="#e6eadd" stroke="#242b25"/><text x="104.0" y="101.0" font-family="Arial, sans-serif" font-size="14" text-anchor="middle" fill="#242b25">React UI</text><rect x="290" y="70" width="180" height="52" rx="6" fill="#e6eadd" stroke="#242b25"/><text x="380.0" y="101.0" font-family="Arial, sans-serif" font-size="14" text-anchor="middle" fill="#242b25">Worker</text><rect x="576" y="70" width="160" height="52" rx="6" fill="#fffef9" stroke="#d9ddd2"/><text x="656.0" y="101.0" font-family="Arial, sans-serif" font-size="14" text-anchor="middle" fill="#242b25">Dataset</text><line x1="184" y1="96" x2="290" y2="96" stroke="#6d7268" stroke-width="1.5"/><polygon points="290,96 282,92 282,100" fill="#6d7268"/><line x1="470" y1="96" x2="576" y2="96" stroke="#6d7268" stroke-width="1.5"/><polygon points="576,96 568,92 568,100" fill="#6d7268"/><text x="237" y="84" font-family="Arial, sans-serif" font-size="12" text-anchor="middle" fill="#6d7268">Init</text><text x="523" y="84" font-family="Arial, sans-serif" font-size="12" text-anchor="middle" fill="#6d7268">Store</text><rect x="24" y="160" width="160" height="48" rx="6" fill="#fffef9" stroke="#d9ddd2"/><text x="104.0" y="189.0" font-family="Arial, sans-serif" font-size="14" text-anchor="middle" fill="#242b25">Region change</text><line x1="184" y1="184" x2="290" y2="184" stroke="#6d7268" stroke-width="1.5"/><polygon points="290,184 282,180 282,188" fill="#6d7268"/><rect x="290" y="160" width="180" height="48" rx="6" fill="#e6eadd" stroke="#242b25"/><text x="380.0" y="189.0" font-family="Arial, sans-serif" font-size="14" text-anchor="middle" fill="#242b25">Aggregate</text><line x1="470" y1="184" x2="576" y2="184" stroke="#6d7268" stroke-width="1.5"/><polygon points="576,184 568,180 568,188" fill="#6d7268"/><rect x="576" y="160" width="160" height="48" rx="6" fill="#fffef9" stroke="#d9ddd2"/><text x="656.0" y="189.0" font-family="Arial, sans-serif" font-size="14" text-anchor="middle" fill="#242b25">Small summary</text><text x="380" y="244" font-family="Arial, sans-serif" font-size="14" text-anchor="middle" fill="#6d7268">Reuse the worker dataset; send only changing filter inputs.</text>
</svg>Send the dataset once, send small filter messages afterwards, and return compact summaries.
Notice that the worker returns aggregated results rather than thousands of raw records. This keeps the communication overhead relatively small and avoids creating a separate rendering bottleneck in the UI.
A worker doesn't guarantee that the result arrives sooner. It can take longer because of worker startup, data transfer and scheduling. The important improvement is that the interface can remain responsive while the result is being prepared.
4. Integrating a worker with React is mostly a lifecycle problem
Starting a worker is simple. Managing it across renders, changing inputs and component unmounts requires more care.
For example, if a user changes a region several times, an earlier result might arrive after the latest selection. Even with one worker processing synchronous messages in sequence, old results can still be displayed after the user has already selected something else.
We can use request IDs and associate every result with the dataset and region that produced it. The following hook creates one worker per mounted hook instance, reinitialises it when the dataset reference changes, and sends a new calculation when the region changes.
// useSalesSummary.js
import { useEffect, useRef, useState } from "react";
export function useSalesSummary(records, region) {
const workerRef = useRef(null);
const latestId = useRef(0);
const [outcome, setOutcome] = useState(null);
const [workerError, setWorkerError] = useState(null);
useEffect(() => {
let worker;
let active = true;
setWorkerError(null);
try {
worker = new Worker(
new URL("./sales.worker.js", import.meta.url),
{ type: "module" }
);
workerRef.current = worker;
worker.onmessage = ({ data }) => {
if (!active || data.id !== latestId.current) return;
// The calculation Effect installs the current receiver.
workerRef.current?.receiveResult?.(data);
};
worker.onerror = event => {
if (active) {
setWorkerError({ records, message: event.message || "Worker failed" });
}
};
worker.onmessageerror = () => {
if (active) {
setWorkerError({ records, message: "Worker message could not be decoded" });
}
};
worker.postMessage({ type: "init", records });
} catch (error) {
worker?.terminate();
workerRef.current = null;
setWorkerError({ records, message: String(error) });
}
return () => {
active = false;
latestId.current++;
worker?.terminate();
if (workerRef.current === worker) workerRef.current = null;
};
}, [records]);
useEffect(() => {
const worker = workerRef.current;
if (!worker) return;
const id = ++latestId.current;
let active = true;
worker.receiveResult = data => {
if (!active || data.id !== id) return;
setOutcome({
records,
region,
rows: data.rows ?? [],
error: data.type === "error" ? data.message : null
});
};
try {
worker.postMessage({ type: "calculate", id, region });
} catch (error) {
setOutcome({ records, region, rows: [], error: String(error) });
}
return () => {
active = false;
latestId.current++;
delete worker.receiveResult;
};
}, [records, region]);
const current = outcome?.records === records &&
outcome?.region === region;
const error = workerError?.records === records
? workerError.message
: current ? outcome.error : null;
return {
rows: current ? outcome.rows : [],
pending: !current && !error,
error
};
}
The worker instance is created inside an Effect, not during rendering. The cleanup terminates it, including during React's development-only Strict Mode setup and cleanup cycle. This avoids leaving a worker running after its owner disappears.
The example attaches a small application-specific callback to the Worker instance to keep the lifecycle and calculation Effects separate. In a larger codebase, a ref or dedicated worker client abstraction may be preferable.
We can now render the report:
import { useState } from "react";
import { useSalesSummary } from "./useSalesSummary.js";
export function SalesDashboard({ records }) {
const [region, setRegion] = useState("all");
const { rows, pending, error } = useSalesSummary(records, region);
return (
<section>
<label>
Region
<select value={region} onChange={e => setRegion(e.target.value)}>
<option value="all">All regions</option>
<option value="Asia">Asia</option>
<option value="Europe">Europe</option>
</select>
</label>
<div aria-live="polite">
{error ? <p>{error}</p> : pending ? <p>Calculating…</p> : (
<ul>
{rows.map(row => (
<li key={row.category}>
{row.category}: {(row.amountCents / 100).toFixed(2)}
</li>
))}
</ul>
)}
</div>
</section>
);
}
Keep records stable between renders when its contents haven't changed. Creating a new array every time the parent renders would restart the worker in this particular implementation, destroying much of the benefit. Treat the dataset as immutable and change its reference when the actual dataset changes.
This is a useful place for memoisation and a worker to work together: memoisation can stabilise derived inputs, while the worker handles the expensive calculation itself.
Ignoring an old result is not the same as cancelling old work
A request ID stops obsolete results from being applied to the UI. It does not stop their calculations from running.
If the user makes ten rapid filter changes, the worker may still process ten messages. A single worker normally handles its synchronous message callbacks one at a time. It cannot process a cancellation message while it is busy inside an uninterrupted loop.
For rapid changes, consider debouncing before posting messages, or a latest-only queue that keeps at most one running calculation and one replacement waiting. For genuinely cancellable algorithms, divide work into chunks and yield so cancellation messages can be handled. Terminating and recreating a worker is another option, but it discards its state and incurs initialization costs.
SVG source
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 760 270" width="760" height="270" role="img" aria-label="Five queued filters compared with one running and one latest waiting filter">
<rect x="0" y="0" width="760" height="270" rx="6" fill="#f6f4ee" stroke="none"/>
<text x="24" y="34" font-family="Arial, sans-serif" font-size="20" text-anchor="start" fill="#242b25">Avoid a backlog of obsolete calculations</text>
<text x="24" y="64" font-family="Arial, sans-serif" font-size="14" text-anchor="start" fill="#6d7268">Every change queued</text><rect x="24" y="80" width="132" height="45" rx="6" fill="#fffef9" stroke="#ab4932"/><text x="90.0" y="107.5" font-family="Arial, sans-serif" font-size="14" text-anchor="middle" fill="#242b25">Filter 1</text><rect x="169" y="80" width="132" height="45" rx="6" fill="#fffef9" stroke="#ab4932"/><text x="235.0" y="107.5" font-family="Arial, sans-serif" font-size="14" text-anchor="middle" fill="#242b25">Filter 2</text><rect x="314" y="80" width="132" height="45" rx="6" fill="#fffef9" stroke="#ab4932"/><text x="380.0" y="107.5" font-family="Arial, sans-serif" font-size="14" text-anchor="middle" fill="#242b25">Filter 3</text><rect x="459" y="80" width="132" height="45" rx="6" fill="#fffef9" stroke="#ab4932"/><text x="525.0" y="107.5" font-family="Arial, sans-serif" font-size="14" text-anchor="middle" fill="#242b25">Filter 4</text><rect x="604" y="80" width="132" height="45" rx="6" fill="#fffef9" stroke="#d9ddd2"/><text x="670.0" y="107.5" font-family="Arial, sans-serif" font-size="14" text-anchor="middle" fill="#242b25">Filter 5</text><text x="24" y="150" font-family="Arial, sans-serif" font-size="14" text-anchor="start" fill="#6d7268">Latest-only policy</text><rect x="24" y="166" width="210" height="50" rx="6" fill="#e6eadd" stroke="#242b25"/><text x="129.0" y="196.0" font-family="Arial, sans-serif" font-size="14" text-anchor="middle" fill="#242b25">Running: filter 1</text><line x1="234" y1="191" x2="320" y2="191" stroke="#6d7268" stroke-width="1.5"/><polygon points="320,191 312,187 312,195" fill="#6d7268"/><rect x="320" y="166" width="230" height="50" rx="6" fill="#e6eadd" stroke="#242b25"/><text x="435.0" y="196.0" font-family="Arial, sans-serif" font-size="14" text-anchor="middle" fill="#242b25">Waiting: filter 5</text><text x="24" y="249" font-family="Arial, sans-serif" font-size="13" text-anchor="start" fill="#6d7268">Replace obsolete waiting requests; the running job may still finish.</text>
</svg>Ignoring stale results protects correctness; coalescing pending work also protects responsiveness.
5. Sending data to a worker isn't free
When you send a normal object to a worker using postMessage, the browser uses structured cloning. The receiving worker obtains a separate representation of the data, not a live reference to the original object.
For small messages this is rarely worth worrying about. For hundreds of megabytes of data, copying and holding two versions in memory may be more expensive than expected.
Typed arrays offer another option: transfer ownership of their underlying ArrayBuffer.
const samples = new Float64Array([12.5, 18.1, 42.0]);
worker.postMessage(
{ type: "samples", buffer: samples.buffer },
[samples.buffer]
);
console.log(samples.byteLength); // 0 after transfer
The buffer is detached from the sender. The worker can reconstruct a typed array from the transferred buffer:
// Separate example of a numeric worker message handler
self.onmessage = ({ data }) => {
const samples = new Float64Array(data.buffer);
let total = 0;
for (const sample of samples) total += sample;
self.postMessage({ total });
};
Transferring an ArrayBuffer avoids copying its backing storage. It does not make every kind of JavaScript object transferable, and it does not eliminate all message overhead.
If the main thread still needs its original typed array, make a deliberate copy before transferring:
const copy = samples.slice();
worker.postMessage({ buffer: copy.buffer }, [copy.buffer]);
Do this before transferring the original, not after it has already been detached. If you're working with a view over a larger buffer, transferring the buffer detaches other views over that same backing storage too. A sliced copy of the view can help isolate exactly the required data.
SVG source
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 760 305" width="760" height="305" role="img" aria-label="Structured clone retains copies while ArrayBuffer transfer detaches the sender">
<rect x="0" y="0" width="760" height="305" rx="6" fill="#f6f4ee" stroke="none"/>
<text x="24" y="34" font-family="Arial, sans-serif" font-size="20" text-anchor="start" fill="#242b25">Copying data vs transferring ownership</text>
<text x="24" y="66" font-family="Arial, sans-serif" font-size="14" text-anchor="start" fill="#6d7268">Structured clone</text><rect x="24" y="82" width="250" height="50" rx="6" fill="#e6eadd" stroke="#242b25"/><text x="149.0" y="112.0" font-family="Arial, sans-serif" font-size="14" text-anchor="middle" fill="#242b25">Sender retains data</text><line x1="274" y1="107" x2="486" y2="107" stroke="#6d7268" stroke-width="1.5"/><polygon points="486,107 478,103 478,111" fill="#6d7268"/><rect x="486" y="82" width="250" height="50" rx="6" fill="#e6eadd" stroke="#242b25"/><text x="611.0" y="112.0" font-family="Arial, sans-serif" font-size="14" text-anchor="middle" fill="#242b25">Receiver gets copy</text><line x1="24" y1="155" x2="736" y2="155" stroke="#d9ddd2" stroke-width="1.5"/><text x="24" y="183" font-family="Arial, sans-serif" font-size="14" text-anchor="start" fill="#6d7268">ArrayBuffer transfer</text><rect x="24" y="199" width="250" height="50" rx="6" fill="#fffef9" stroke="#ab4932"/><text x="149.0" y="229.0" font-family="Arial, sans-serif" font-size="14" text-anchor="middle" fill="#242b25">Sender detached</text><line x1="274" y1="224" x2="486" y2="224" stroke="#6d7268" stroke-width="1.5"/><polygon points="486,224 478,220 478,228" fill="#6d7268"/><rect x="486" y="199" width="250" height="50" rx="6" fill="#e6eadd" stroke="#242b25"/><text x="611.0" y="229.0" font-family="Arial, sans-serif" font-size="14" text-anchor="middle" fill="#242b25">Receiver owns buffer</text><text x="380" y="283" font-family="Arial, sans-serif" font-size="13" text-anchor="middle" fill="#6d7268">Transfer ownership only when the sender no longer needs the buffer.</text>
</svg>Cloning retains independent copies. Transferring a buffer moves ownership and detaches it from the sender.
The HTML Standard's structured data rules and MDN's transferable objects guide explain these semantics in more detail.
For our sales dashboard, sending the dataset once and returning small summaries is probably a better initial optimisation than converting every field to binary. Profile the transfer cost before introducing a more complex data representation.
6. Measure responsiveness and completion time separately
A worker can improve one metric while making another worse.
Imagine a calculation that takes 120 ms on the main thread. Moving it to a worker adds 15 ms of messaging and scheduling overhead in a hypothetical test. The result now takes 135 ms, but input handling may no longer be blocked for the entire calculation.
These numbers are illustrative, not measured benchmarks. The worker could be faster or slower depending on the device and workload.
There are at least three things worth measuring:
- Time from input to the next visible response.
- Time from calculation submission to result availability.
- Main-thread work, memory use and communication overhead.
You can start by measuring round-trip latency:
const startedAt = new Map();
function calculate(id, region) {
startedAt.set(id, performance.now());
worker.postMessage({ type: "calculate", id, region });
}
worker.addEventListener("message", ({ data }) => {
const start = startedAt.get(data.id);
if (start === undefined) return;
startedAt.delete(data.id);
console.log("Round trip:", performance.now() - start, "ms");
});
In a complete client, also clear outstanding timing entries when the worker fails or terminates. Measure worker-side computation separately using performance.now() inside the worker; send the elapsed duration back rather than subtracting timestamps from different contexts.
The browser Performance panel can reveal long tasks on the main thread and worker activity. React's Profiler helps identify expensive component rendering and commits, but it won't by itself explain every cost outside React. Try a production build, realistic datasets and lower-powered devices rather than relying solely on your development machine.
The Long Tasks API, where supported, can report main-thread tasks of at least 50 ms. Treat that threshold as a diagnostic signal, not a universal UX target. Interaction to Next Paint (INP) provides another useful perspective on interaction responsiveness.
A worker also won't fix a page that renders 100,000 DOM elements after receiving its answer. That is a rendering problem, for which pagination, list virtualisation or smaller results may help more.
7. When should you actually choose a worker?
| Problem | Starting point |
|---|---|
| Same expensive calculation repeats with unchanged inputs | useMemo or compiler-assisted memoisation |
| A slow React subtree competes with typing | State isolation, memoisation, deferred rendering |
| A long CPU-bound calculation monopolises the main thread | Dedicated Web Worker |
| Many duplicate calculations are queued | Debouncing, coalescing or caching |
| Network response is slow | Improve network/API behaviour; a worker is not a cure for latency |
| A large result is expensive to render | Pagination or virtualisation |
| Data copying dominates worker execution | Smaller messages, transferable buffers, persistent worker state |
Good worker candidates include image processing, large client-side data transformations, complex document parsing, local search indexing and computational simulations. Ordinary API calls and small array operations often do not justify another execution context.
Avoid creating a worker per keystroke or per individual record. Worker creation, memory use and message handling have costs. A pool can help independent CPU-bound jobs, but too many workers compete for cores, memory bandwidth and power. One persistent worker is often a sensible first experiment.
Workers also are not a durable background job system. Closing the page or terminating the worker can stop its work. If an operation must survive browser shutdown, use an appropriate server-side job architecture instead.
Final thoughts
useMemo is valuable when your application repeats calculations that could have been avoided. It is less useful when every new input genuinely requires an expensive calculation.
A Web Worker offers a different trade-off. It introduces a communication boundary and some overhead, but it gives computational work somewhere else to run.
Rather than asking whether a worker is faster than useMemo, ask what you are trying to improve. Are you reducing repeated work, improving interaction responsiveness, or reducing the time until the result is available?
Those goals are related, but they're not interchangeable.
The best optimisation might be a better algorithm. It might be a cached result. Or it might be moving the work off the main thread entirely.
THE CONVERSATION
Comments
Questions, useful examples and different approaches are welcome. Keep the discussion thoughtful and on topic.
Loading comments…