UNPKG

rooks

Version:

Collection of awesome react hooks

80 lines (79 loc) 2.11 kB
/** * Status of the web worker */ type WorkerStatus = "idle" | "running" | "success" | "error" | "terminated"; /** * Return value for the useWebWorker hook */ interface UseWebWorkerReturnValue<T = any> { /** * Post a message to the web worker * @param message - The message to send to the worker */ postMessage: (message: any) => void; /** * Terminate the web worker */ terminate: () => void; /** * The current status of the web worker */ status: WorkerStatus; /** * The last data received from the worker */ data: T | null; /** * Any error that occurred */ error: Error | null; /** * Whether Web Workers are supported */ isSupported: boolean; } /** * useWebWorker hook * * Simplified Web Worker management with message passing. * Provides an easy way to offload heavy computations to a background thread * without blocking the main UI thread. * * @param workerUrl - The URL to the worker script file * @returns Object containing worker operations and state * * @example * ```tsx * import { useWebWorker } from "rooks"; * * function HeavyComputationComponent() { * const { postMessage, data, status, error, terminate, isSupported } = * useWebWorker<number>("/worker.js"); * * const handleCompute = () => { * postMessage({ type: "compute", value: 1000000 }); * }; * * if (!isSupported) { * return <div>Web Workers not supported</div>; * } * * return ( * <div> * <button onClick={handleCompute} disabled={status === "running"}> * Start Computation * </button> * <button onClick={terminate}>Terminate</button> * <p>Status: {status}</p> * {data !== null && <p>Result: {data}</p>} * {error && <p>Error: {error.message}</p>} * </div> * ); * } * ``` * * @see https://rooks.vercel.app/docs/hooks/useWebWorker */ declare function useWebWorker<T = any>(workerUrl: string): UseWebWorkerReturnValue<T>; export { useWebWorker }; export type { UseWebWorkerReturnValue, WorkerStatus };