Skip to content

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.

PropertyTypeRequiredDescription
urlstring \| URLURL of the worker script to load. Must comply with the same-origin policy (or use a Blob URL for inline workers).
optionsWorkerOptionsOptions forwarded to the Worker constructor (e.g. { type: "module" }).
onMessage(e: MessageEvent) => voidCalled on the main thread when the worker posts a message via postMessage.
onMessageError(e: MessageEvent) => voidCalled when the worker receives a message that cannot be deserialised.
onError(e: Event) => voidCalled when an uncaught error occurs inside the worker.

UseWebWorkerResult

Result object returned by useWebWorker.

PropertyTypeRequiredDescription
send<T>(message: T, transfer?: Transferable[] \| StructuredSerializeOptions) => voidPost a message to the worker thread.
terminateWorker["terminate"]Immediately terminate the worker, stopping its execution. Any pending messages are discarded.

Released under the MIT License.