A hook that exposes a function that offloads its computations to an isolated thread facilitated by a web worker and returns a promise.
import { useWorkerFunc } from 'use-react-hooks';
interface Controller { status: 'idle' | 'running' | 'error' | 'expired' | 'killed'; terminate: () => void;} interface Options { timeout?: number; remoteDependencies?: string[]; autoTerminate?: boolean; transferable?: 'auto' | 'none';} const useWorkerFunc = <T extends (args: any[]) => any>( func: T, options?: Options) => [(args: Parameters<T>) => Promise<ReturnType<T>>, Controller];
import React from 'react';import { useWorkerFunc } from 'use-react-workers'; // Heavy compute functionfunction fibonacci(n: number): number { return n <= 1 ? n : fib(n - 1) + fib(n - 2);} const MyCoolComponent = () => { const [fibWorker] = useWorkerFunc(fibonacci); const withWorker = async () => { const result = await fibWorker(45); // Will not block the main thread 🥳 console.log(result); }; const without = () => { const result = fibonacci(45); // Main thread is blocked 😪 console.log(result); }; return ( <div className="flex gap-4"> <button className="btn" onClick={withWorker}> With Worker </button> <button className="btn" onClick={without}> Without Worker </button> </div> );};