Skip to content

useWebWorker

Category
Export Size
371 B
Last Changed
5 days ago
Related

Simple Web Workers registration and communication

Demo

Usage

tsx
import { 
useWebWorker
} from '@reause/core'
const {
data
,
post
,
terminate
,
worker
} =
useWebWorker
('/path/to/worker.js')
StateTypeDescription
dataData | nullLatest data received via the worker (e.data), null until the first message arrives
workerWorker | undefinedThe Web Worker instance, undefined until the mount effect created it
MethodSignatureDescription
post(message: any, transfer: Transferable[]): void
(message: any, options?: StructuredSerializeOptions | undefined): void
Sends data to the worker thread.
terminate() => voidStops and terminates the worker.

Worker instance / factory overload

useWebWorker also accepts an existing Worker instance or a factory function returning one, instead of a URL (upstream's second overload, useWebWorker(worker: Worker | WorkerFn)):

tsx
import { 
useWebWorker
} from '@reause/core'
// adopt an existing instance (its `onmessage` is wired; terminated on unmount) const
external
= new
Worker
('/path/to/worker.js')
const {
data
} =
useWebWorker
(
external
)
// or a factory function returning a Worker const {
data
:
factoryData
} =
useWebWorker
(() => new
Worker
('/path/to/worker.js'))

An adopted instance is terminated when the component unmounts, including the synthetic unmount of a React StrictMode remount cycle — prefer the factory-function form when StrictMode is enabled.

Window option

The optional third argument accepts a window option (defaults to the global window) used as the creation guard, mirroring upstream's if (window) check: a falsy window skips worker creation entirely, so SSR renders worker: undefined and post becomes a no-op:

tsx
const { 
worker
} =
useWebWorker
('/path/to/worker.js',
undefined
, {
window
: null as unknown as Window })

Type Declarations

ts
export interface UseWebWorkerReturn<Data = any> {
    data: Data | null;
    post: PostMessage;
    terminate: () => void;
    worker: Worker | undefined;
}

type PostMessage = typeof Worker.prototype['postMessage']

interface UseWebWorkerOptions {
    window?: Window;
}

type WorkerFn = (...args: unknown[]) => Worker

export function useWebWorker<T = any>(url: string, workerOptions?: WorkerOptions, options?: UseWebWorkerOptions): UseWebWorkerReturn<T>

export function useWebWorker<T = any>(worker: Worker | WorkerFn): UseWebWorkerReturn<T>

Source

Source · Demo · VueUse

Contributors

hairyf

Changelog

v0.1.0 on
e8a55 - fix(core): resolve useWebWorker audit findings (#693)
30916 - fix(test): stabilize flaky timing-sensitive browser tests

Released under the MIT License. v0.1.8