useWebWorker
Creates and manages a classic Web Worker with message, status, and error state.
About
useWebWorker creates a classic Worker from a URL after mount and exposes message passing, termination, and the last response or error. It does not turn a function into worker code; the worker script remains a separate browser program.
Examples
"use client";
import { useEffect, useState } from "react";
import { useWebWorker } from "rooks";
const source = "self.onmessage = (event) => self.postMessage(event.data * 2);";
export default function WorkerDemo() {
const [workerUrl, setWorkerUrl] = useState("");
useEffect(() => {
const url = URL.createObjectURL(
new Blob([source], { type: "text/javascript" })
);
setWorkerUrl(url);
return () => URL.revokeObjectURL(url);
}, []);
const worker = useWebWorker<number>(workerUrl);
return (
<section>
<button type="button" onClick={() => worker.postMessage(21)}>
Double 21
</button>
<button type="button" onClick={worker.terminate}>
Terminate
</button>
<p role="status">
{!workerUrl
? "Preparing worker"
: worker.isSupported
? `${worker.status}: ${worker.data ?? "no result"}`
: "Workers unavailable"}
</p>
{worker.error && <p role="alert">{worker.error.message}</p>}
</section>
);
}Parameters
workerUrl: string is required. An empty string leaves the hook idle. The hook calls new Worker(workerUrl) without module-worker options.
Return value
The returned object has this inline shape:
| Property | Type | Meaning |
|---|---|---|
postMessage | (message: TMessage) => void | Sends a structured-cloneable message. |
terminate | () => void | Stops the current worker and marks it terminated. |
status | "idle" | "running" | "success" | "error" | "terminated" | Latest lifecycle status. |
data | TData | null | Last message data received. |
error | Error | null | Last creation, post, or worker error. |
isSupported | boolean | Whether window.Worker exists. |
These result and status types are not public type exports from the package barrel.
Behavior and lifecycle
The effect creates one worker per non-empty URL. A URL change terminates the old worker and constructs another, but existing data and status are not reset first. Posting marks status running and clears the error. Any received message marks success; the hook does not count multiple outstanding tasks. Worker errors mark error. Creation and structured-clone errors become Error state.
Explicit termination nulls the worker ref, so later posts warn "Worker not initialized"; restarting requires a URL change or remount. Unmount terminates the worker without setting component state.
Compatibility and accessibility
Server rendering reports unsupported. Rendering that branch directly can differ from the first client render, so use a client boundary or hydration-safe placeholder. Worker URLs must satisfy origin and Content Security Policy rules, workers cannot access the DOM, and messages use structured cloning. Give long-running work visible progress, a useful error, and a keyboard-operable cancellation control.