FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Transformers.js in React: Worker and Pipeline Lifecycles

Share one Transformers.js pipeline load in a browser worker, report model progress, and keep React cleanup or stale responses from duplicating work.

Freshness: current•10 min read•Deep Learning and Specialized AI
Full Technical Reference Document

Mental model

Load Transformers.js in a browser worker, share the pending pipeline promise for a model configuration, and let React subscribe to progress and results. Strict Mode may run effect setup, cleanup, and setup again; reusing the worker and detaching only the old listener avoids duplicate initialization, while request IDs prevent late inference from replacing newer UI state.

There are two useful caches with different lifetimes. A worker-local promise is a single-flight cache: simultaneous requests for the same task, repository, revision, and dtype await one pipeline initialization. Transformers.js also downloads model files into the browser cache, which can speed up a later worker or page load. The promise prevents duplicate loading while a worker is alive; the browser cache stores assets and may be evicted. Neither cache means the model is already resident after a component rerenders.

Keep the pipeline outside React render. Creating it in a component body repeats initialization on each render; creating it at module scope in a server-rendered bundle can touch browser APIs before a client exists. Instead, create a module worker from a client-only effect or user action. The worker owns pipeline initialization and inference, while React owns text, progress, status, and the latest request identifier. A small typed message protocol connects them.

Learning outcomes

  • Given model bytes and a network rate, estimate the ideal transfer time and identify which additional measurements contribute to first-prediction delay.
  • Trace a prediction from a React event through a worker message, one shared pipeline promise, and a correlated result or error.
  • Design an effect cleanup that survives Strict Mode setup-cleanup-setup while discarding replies for changed input or an unmounted component.

Theory

Pipeline initialization and single-flight loading

Transformers.js exposes the pipeline(task, model, options) factory. Its first call downloads model files, loads tokenizer and model state, and creates the task pipeline; the returned function performs preprocessing, model inference, and task-specific postprocessing. For text classification, one string input resolves to a list of label/score results; the worker sends only those primitive fields across the message boundary. In-browser calls use quantized weights by default in the documented pipeline API; an explicit dtype such as q8 makes the memory/accuracy choice visible. A production cache key should include task, model repository, immutable revision, dtype, and execution device. If any of those change, a previous pipeline is not interchangeable.

Store the promise before awaiting it. This matters because two consumers can request the model during the same network or initialization interval. If each call starts pipeline() before either finishes, they can create competing downloads, memory allocations, and runtime sessions. A shared pending promise makes later callers wait for the first initialization. On initialization failure, clear only that rejected promise so a later user action can retry; do not clear a healthy pipeline merely because one inference input was invalid.

The progress callback reports file-level load activity. Forward those events from the worker with a file name and percentage, then render them as status instead of freezing the page behind an indefinite spinner. A thrown download, model-format, unsupported operator, or inference error should become a structured error message. Keep the full exception in diagnostic logs where appropriate, but show a useful bounded message in the interface.

React setup, cleanup, and request identity

React effects synchronize a mounted component with an external system such as a Worker. In development Strict Mode, React intentionally runs an extra setup-cleanup cycle before the lasting setup. That is a lifecycle check, not a signal to weaken Strict Mode. A correct effect removes its own message listener and marks its outstanding request stale; it should not tear down a shared worker immediately if the next setup will reuse the same model.

A worker singleton can be acquired by effects and released after an idle grace period. The Strict Mode second setup cancels that pending disposal and attaches a new listener to the same worker. After a real unmount with no consumers, a timer terminates the worker so GPU and model memory do not remain resident indefinitely. If a later screen needs the model after disposal, Transformers.js can reuse cached files while it rebuilds runtime state.

Every inference request gets a monotonically increasing identifier. When the user submits newer text, increment the identifier; when the effect cleans up, increment it again. The component applies a result or error only if its identifier still matches the latest one. This is the same stale-response guard needed when network requests return out of order. It does not cancel a computation already submitted to a worker, but prevents that computation from overwriting newer UI state.

First-prediction cost model

Suppose a model's ONNX weights and tokenizer files total 120 MiB, and a user has a 30 Mbit/s connection. The files contain 125,829,120 bytes, so the ideal transfer floor is 8 × 125,829,120 / 30,000,000 = 33.55 seconds before protocol overhead or model initialization. If a measured test device needs 4 seconds to parse assets and 5 seconds to compile or initialize its runtime, the ready time is about 42.55 seconds. Sharing one load promise avoids starting a second initialization during that wait; a progress callback still matters because one correct download can take tens of seconds.

The approximate model is:

Tready≈8BmodelRlink+Tparse+TcompileT_{\text{ready}} \approx \frac{8B_{\text{model}}}{R_{\text{link}}} + T_{\text{parse}} + T_{\text{compile}}

Here, Bmodel is downloaded model and tokenizer data in bytes, Rlink is throughput in bits per second, and each T is a measured time in seconds. The equation omits cache hits, retries, decompression, storage latency, and device-specific kernel setup. Record cold and warm starts separately; do not present this lower bound as observed inference latency.

Worker and component implementation

This example keeps the model promise inside one module worker and creates the shared worker only when a client effect mounts. The worker posts progress to every listener, while request identifiers gate result and error messages. The 30-second idle grace reuses the initialized worker across Strict Mode's immediate cleanup/setup cycle, then frees it when the feature is genuinely unused.

typescript
// classifier.worker.ts
import { pipeline } from "@huggingface/transformers";
const MODEL_ID = "Xenova/distilbert-base-uncased-finetuned-sst-2-english";
type Job = { type: "classify"; clientId: number; id: number; text: string };
type Prediction = { label: string; score: number };
type Classifier = (text: string) => Promise<Prediction[]>;
let classifierPromise: Promise<Classifier> | undefined;
function getClassifier() {
if (!classifierPromise) {
const pending = pipeline("text-classification", MODEL_ID, { dtype: "q8", progress_callback: (p) => self.postMessage({ type: "progress", file: p.file ?? MODEL_ID, progress: p.progress ?? 0 }) }).then((pipe) => pipe as unknown as Classifier);
classifierPromise = pending;
void pending.catch(() => { if (classifierPromise === pending) classifierPromise = undefined; });
}
return classifierPromise!;
}
self.addEventListener("message", async (event: MessageEvent<Job>) => {
const job = event.data; if (job.type !== "classify") return;
try {
const classifier = await getClassifier(); self.postMessage({ type: "inference", clientId: job.clientId, id: job.id });
const [prediction] = await classifier(job.text);
self.postMessage({ type: "result", clientId: job.clientId, id: job.id, label: prediction.label, score: prediction.score });
} catch (cause) { self.postMessage({ type: "error", clientId: job.clientId, id: job.id, message: cause instanceof Error ? cause.message : String(cause) }); }
});

The component and worker are separate files; only the effect acquires the worker, so server rendering does not evaluate browser APIs.

tsx
import { useEffect, useRef, useState } from "react";
type Reply = { type: "progress"; file: string; progress: number } | { type: "inference"; clientId: number; id: number } | { type: "result"; clientId: number; id: number; label: string; score: number } | { type: "error"; clientId: number; id: number; message: string };
let sharedWorker: Worker | undefined; let users = 0; let idleTimer: number | undefined; let nextClientId = 0;
function acquireWorker() { if (idleTimer !== undefined) window.clearTimeout(idleTimer); sharedWorker ??= new Worker(new URL("./classifier.worker.ts", import.meta.url), { type: "module" }); users++; return sharedWorker; }
function releaseWorker() { if (--users === 0) idleTimer = window.setTimeout(() => { sharedWorker?.terminate(); sharedWorker = undefined; }, 30_000); }
export function ClassifierDemo() {
const [text, setText] = useState(""); const [phase, setPhase] = useState("Idle");
const [file, setFile] = useState(""); const [progress, setProgress] = useState(0); const [result, setResult] = useState(""); const [error, setError] = useState("");
const [ready, setReady] = useState(false); const clientId = useRef<number | null>(null); const workerRef = useRef<Worker | null>(null); const latest = useRef(0);
useEffect(() => {
const id = ++nextClientId; clientId.current = id; let worker: Worker;
try { worker = acquireWorker(); } catch (cause) { setError(cause instanceof Error ? cause.message : String(cause)); setPhase("Error"); return; }
workerRef.current = worker; setReady(true);
const onMessage = (event: MessageEvent<Reply>) => {
const message = event.data;
if (message.type === "progress") { setFile(message.file); setProgress(message.progress); setPhase("Loading model"); return; }
if (message.clientId !== id || message.id !== latest.current) return;
if (message.type === "inference") { setPhase("Classifying"); return; }
if (message.type === "result") { setResult(message.label + " (" + message.score.toFixed(3) + ")"); setPhase("Ready"); setError(""); }
else { setError(message.message); setPhase("Error"); }
};
worker.addEventListener("message", onMessage);
return () => { latest.current++; clientId.current = null; worker.removeEventListener("message", onMessage); workerRef.current = null; releaseWorker(); };
}, []);
const run = () => {
const value = text.trim(); if (!value || value.length > 4000) return;
const client = clientId.current; if (client === null) return;
const id = ++latest.current; setPhase("Loading or classifying"); setResult(""); setError("");
workerRef.current?.postMessage({ type: "classify", clientId: client, id, text: value });
};
return <section><textarea value={text} maxLength={4000} onChange={(event) => { latest.current++; setText(event.target.value); setPhase("Idle"); setResult(""); setError(""); }} /><button disabled={!ready || !text.trim()} onClick={run}>Classify locally</button><p>{phase}: {file}</p><progress max={100} value={progress} /><output>{result}</output><p role="alert">{error}</p></section>;
}

Trade-offs

Lazy loading avoids downloading a large model for users who never open the feature, but the first interested user sees the full cold-start cost. Preloading during idle time can hide some latency, but spends bandwidth, memory, and battery before intent is clear. Keep a worker alive briefly to absorb route transitions and Strict Mode checks; a longer grace period improves reuse but retains model memory while hidden. A smaller quantized pipeline usually loads faster, though classification scores and labels still need evaluation against the application's quality target.

A browser worker moves pipeline execution and model parsing away from the UI thread; it does not reduce total CPU or GPU work. Large messages still incur structured-clone cost, so send bounded text and compact metadata rather than transferring a whole application state. A worker also needs an explicit browser support policy, a recoverable error state, and accessible progress text. If a model exceeds the device budget or supported operator set, compare a smaller local model or an approved remote service using the same input and quality checks.

Failure modes and misconceptions

Creating pipeline() during render is not a cache. Every render can start another initialization, while a module-level call can run during server rendering where Worker and browser storage do not exist. Put browser-only construction behind a client effect, and keep the shared worker and promise at module scope only as inert declarations until that effect runs.

Terminating the worker in every effect cleanup breaks Strict Mode's setup-cleanup-setup probe: the second setup creates a new worker and can repeat parsing, model initialization, or a network request that had not finished. Conversely, keeping a rejected promise forever makes every later attempt fail immediately. Retain a pending or fulfilled promise, clear the same promise only when initialization rejects, and defer worker disposal while another component or immediate remount may reuse it.

Out-of-order inference replies can display a prediction for text the user has already changed. Ignore results whose request ID is stale, and invalidate the active ID during effect cleanup. Progress events describe a shared model load rather than a particular prediction, so they can be broadcast without an inference ID; errors and results should carry the request ID. A progress event is not proof that the final model loaded successfully: report a distinct ready, result, or error state.

Moving work to a worker does not make the model free. Browser cache eviction, offline use, version changes, and low storage can all force a new asset load or a terminal error. Pin model revisions for reproducibility, handle rejected downloads and unsupported model files, and let a user retry or choose another route. A successful worker message also does not measure an accurate prediction; compare labels and scores with a trusted evaluation set before changing product decisions.

Decision scenario

A support team wants local sentiment classification for private feedback. The selected model package is 120 MiB, and field measurements show a 30 Mbit/s connection with about 4 seconds of asset parsing and 5 seconds of runtime initialization. A React page in development Strict Mode mounts the classifier twice, while users can edit text before an earlier classification reply returns. Create the worker only after the feature mounts, share one in-flight pipeline promise keyed by model revision and dtype, stream file progress, and correlate each result with the current request ID. Let cleanup remove its listener and schedule worker disposal after an idle grace period. Before rollout, compare the cold-start experience and quality on representative devices; if the delay or memory use misses the product budget, use a smaller validated model or an approved remote path instead of hiding the delay or accepting stale predictions.

Mount client feature
Acquire shared module worker
Resolve cached pipeline promise
Report model progress and classify input
Apply only current request result or error
Conceptual teaching model synthesized from:hf-transformers-js-docs,transformers-js-pipelines-docs,react-useeffect-reference
Reflect before revealing the guide

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next