中文 | English
A powerful React hook for easy Web Worker integration with TypeScript support, automatic cleanup, and comprehensive error handling.
📖 For more information, read 👉 Documentation 👈
- 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
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>
);
}
Creates a Web Worker function Hook that provides execution methods.
const [workerFn, workerStatus, workerTerminate] = useWebWorkerFn(
fn: T,
options?: UseWebWorkerFnOptions
);
fn: T
- Function to run in Web Workeroptions?: UseWebWorkerFnOptions
- Configuration options
interface UseWebWorkerFnOptions {
dependencies?: string[]; // External script URLs
localDependencies?: string[]; // Local script paths
timeout?: number; // Timeout in milliseconds
onError?: (error: Error) => void; // Error callback
}
workerFn: (...args: Parameters<T>) => Promise<ReturnType<T>>
- Function to execute workerworkerStatus: WebWorkerStatus
- Worker statusworkerTerminate: (status?: WebWorkerStatus) => void
- Function to terminate worker
A hook for more direct Web Worker control.
const [data, post, terminate, status] = useWebWorker(
script: string | URL,
options?: UseWebWorkerOptions
);
Contributions are welcome! Please feel free to submit a Pull Request.
MIT License