useWebWorkerFn
Hook to run expensive functions using a Web Worker without blocking the UI handling execution as Promise.
Demo
INFO
The component uses useWebWorkerFn hook to execute an expensive function in a worker. Same function can be executed in main thread. Try to execute it to see the differences.
Loading demo…
Show source code
tsx
import { useCallback, useEffect, useState } from "react";
import { useWebWorkerFn } from "../../../..";
export const UseWebWorkerFn = () => {
const [ts, setTs] = useState(new Date());
const [mess, setMess] = useState<string>("");
const heavyTask = useCallback(() => {
const numbers: number[] = Array(5_000_000).fill(true).map(() => Math.random() * 11)
return numbers.slice(0, 5).map(el => Math.floor(el))
}, []);
const execute = useWebWorkerFn(heavyTask);
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...");
setMess(heavyTask().join(","))
}}
>
Start in Main Thread
</button>
<button
onClick={() => {
setMess("Pending...");
execute().then(res => setMess(res.join(",")));
}}
>
Start in Web Worker
</button>
</div>
}Types
UseWebWorkerFnProps
@templateT - The type of the function to execute inside the Web Worker. Must be a callable accepting any number of arguments and returning any value.
Props accepted by useWebWorkerFn.
| Property | Type | Required | Description |
|---|---|---|---|
fn | T | ✓ | The function to run inside a Web Worker. It is serialised via .toString() and reconstructed in an isolated worker context, so it must be a pure, self-contained function — it cannot reference variables, imports, or closures from the outer scope. Any dependencies must either be passed as arguments or loaded via deps. |
deps | string[] | An optional array of external script URLs imported into the worker context via importScripts() before fn is invoked. Use this to provide third-party libraries, polyfills, or shared utilities that fn depends on at runtime. |
UseWebWorkerFnResult
@templateT - The type of the original function, used to preserve its parameter and return types.
Return value of useWebWorkerFn.
An async wrapper function with the same parameter signature as fn. Calling it serialises the arguments, transfers them to the Web Worker, executes fn in the isolated worker context, and resolves the returned Promise with the result once the worker replies. Rejects if the worker throws or is terminated before completing.
| Input | Input Description | Return | Return Description |
|---|---|---|---|
(...args: Parameters<T>) | args - The arguments forwarded to fn inside the worker. Must be serialisable via the structured clone algorithm. | Promise<ReturnType<T>>; | A Promise that resolves with the return value of fn, or rejects if the worker encounters an error. |
