useWebWorker
Hook to use Web Worker, handling registration and communication.
See: Web Worker.
Demo
INFO
The component uses useWebWorker hook to execute an heavy function in a worker to avoid burdening the main thread.
Loading demo…
Show source code
tsx
import { useCallback, useEffect, useState } from "react";
import { useWebWorker } from "../../../.."
export const UseWebWorker = () => {
const [ts, setTs] = useState(new Date());
const [mess, setMess] = useState<string>("");
const { send } = useWebWorker({
url: new URL('./worker.ts', import.meta.url),
onMessage: useCallback((e: MessageEvent) => {
setMess(e.data.res.join(","))
}, [])
});
useEffect(() => {
const id = setInterval(() => setTs(new Date()), 1);
return () => clearInterval(id);
}, []);
return <div>
<p>Timestamp: {ts.toLocaleString() + "." + ts.getMilliseconds()}</p>
<p>Result: {mess ? mess : ""}</p>
<button
onClick={() => {
setMess("Pending...");
send("heavyTask");
}}
>
START
</button>
</div>
}Types
UseWebWorkerProps
Props for the useWebWorker.
| Property | Type | Required | Description |
|---|---|---|---|
url | string \| URL | ✓ | URL of the worker script to load. Must comply with the same-origin policy (or use a Blob URL for inline workers). |
options | WorkerOptions | Options forwarded to the Worker constructor (e.g. { type: "module" }). | |
onMessage | (e: MessageEvent) => void | Called on the main thread when the worker posts a message via postMessage. | |
onMessageError | (e: MessageEvent) => void | Called when the worker receives a message that cannot be deserialised. | |
onError | (e: Event) => void | Called when an uncaught error occurs inside the worker. |
UseWebWorkerResult
Result object returned by useWebWorker.
| Property | Type | Required | Description |
|---|---|---|---|
send | <T>(message: T, transfer?: Transferable[] \| StructuredSerializeOptions) => void | ✓ | Post a message to the worker thread. |
terminate | Worker["terminate"] | ✓ | Immediately terminate the worker, stopping its execution. Any pending messages are discarded. |
