fn

useWebWorker

v0.0.14testeddemo

Simple Web Worker communication with reactive incoming data and automatic teardown

Examples

ts
const { data, post, terminate } = useWebWorker('/worker.js');
post({ type: 'start' });
watch(data, value => console.log(value));
ts
const { data } = useWebWorker(() => new Worker(new URL('./worker.ts', import.meta.url)));

Demo

Loading demo…

Signature

ts
export function useWebWorker<Data = unknown>(
  source: WebWorkerSource,
  options: UseWebWorkerOptions ={ ... }

Type Parameters

Data= unknown

Parameters

ParameterTypeDescription
sourceWebWorkerSourceA Worker instance, a script URL/string, or a factory returning a Worker
options?UseWebWorkerOptionsWorker constructor options and message/error hooks

Returns

UseWebWorkerReturn<Data>{ data, post, terminate, worker, isSupported }
PropertyTypeDescription
dataShallowRef<Data | null>The latest data received from the worker via postMessage
postWorkerPostMessageSend a message to the worker. No-op when the worker is unavailable.
terminateVoidFunctionTerminate the worker immediately and release the reference.
workerShallowRef<Worker | undefined>The underlying Worker instance, or undefined when unsupported / terminated.
isSupportedShallowRef<boolean>Whether Worker is available in the current environment (SSR-safe).