Skip to content

atom-universe/useWebWorker

Repository files navigation

useWebWorker Logo

useWebWorker

中文 | English

A powerful React hook for easy Web Worker integration with TypeScript support, automatic cleanup, and comprehensive error handling.

NPM version NPM downloads

📖 For more information, read 👉 Documentation 👈

Quick Start

  • Zero Dependencies, Lightweight - Pure React hooks with no external dependencies
  • Function-like API - Use Web Workers just like calling regular functions
  • Automatic Cleanup - Workers are automatically terminated when components unmount
npm install @atom-universe/use-web-worker

Basic Usage

import { useWebWorkerFn } from '@atom-universe/use-web-worker';

function App() {
  const [workerFn, status] = useWebWorkerFn((a: number, b: number) => a + b);

  const handleClick = async () => {
    const result = await workerFn(1, 2);
    console.log(result); // 3
  };

  return (
    <div>
      <button onClick={handleClick}>Calculate</button>
      <div>Current status: {status}</div>
    </div>
  );
}

API Reference

useWebWorkerFn

Creates a Web Worker function Hook that provides execution methods.

const [workerFn, workerStatus, workerTerminate] = useWebWorkerFn(
  fn: T,
  options?: UseWebWorkerFnOptions
);

Parameters

  • fn: T - Function to run in Web Worker
  • options?: UseWebWorkerFnOptions - Configuration options

Options

interface UseWebWorkerFnOptions {
  dependencies?: string[]; // External script URLs
  localDependencies?: string[]; // Local script paths
  timeout?: number; // Timeout in milliseconds
  onError?: (error: Error) => void; // Error callback
}

Returns

  • workerFn: (...args: Parameters<T>) => Promise<ReturnType<T>> - Function to execute worker
  • workerStatus: WebWorkerStatus - Worker status
  • workerTerminate: (status?: WebWorkerStatus) => void - Function to terminate worker

useWebWorker

A hook for more direct Web Worker control.

const [data, post, terminate, status] = useWebWorker(
  script: string | URL,
  options?: UseWebWorkerOptions
);

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

MIT License