npm package: @okaygift/react-use-worker
Description: A simple React hook to run expensive functions in a background thread using Web Workers, without blocking the UI.
Author: OkayGift
Latest version: 1.0.0

React Use Worker
A simple React hook to run expensive functions in a background thread using Web Workers, preventing the UI from freezing.

The Problem
In a standard React application, all JavaScript code runs on a single "main thread." If you need to perform a CPU-intensive task—like processing a large dataset, performing complex calculations, or parsing a large file—it will block this main thread. While the task is running, the user's browser will become completely unresponsive. They won't be able to click buttons, scroll, or interact with your app in any way.

The Solution
Web Workers provide a way to run JavaScript in a background thread, separate from the main UI thread. However, the standard API for using them (postMessage, onmessage) is event-based and doesn't fit nicely into the declarative, hook-based model of React.

useWorker is a simple hook that wraps the complexity of Web Workers in a familiar, hook-based API. It allows you to run a function in the background and receive its result as state.

Installation
npm install @your-username/react-use-worker

How to Use
The useWorker hook takes a function and an array of its arguments. It returns an object containing the status of the worker, the data it returned, or any error that occurred.

import { useWorker } from '@your-username/react-use-worker';

// A simple (but potentially slow) function to find prime numbers.
// IMPORTANT: This function must be self-contained and not use any variables
// from its surrounding scope.
const findPrimes = (limit: number) => {
  const primes = [];
  for (let i = 2; i <= limit; i++) {
    let isPrime = true;
    for (let j = 2; j < i; j++) {
      if (i % j === 0) {
        isPrime = false;
        break;
      }
    }
    if (isPrime) {
      primes.push(i);
    }
  }
  return primes;
};

function PrimeCalculator() {
  const [limit, setLimit] = useState(10000);
  
  // Run the `findPrimes` function in a background thread.
  // The worker will re-run automatically if the `limit` dependency changes.
  const { data, error, status } = useWorker(findPrimes, [limit]);

  return (
    <div>
      <h2>Prime Number Calculator</h2>
      <input
        type="number"
        value={limit}
        onChange={(e) => setLimit(Number(e.target.value))}
      />
      
      {status === 'running' && <p>Calculating...</p>}
      {status === 'error' && <p>Error: {error?.message}</p>}
      {status === 'success' && (
        <p>Found {data?.length} primes up to {limit}.</p>
      )}
    </div>
  );
}

API
useWorker(fn, fnArgs)
Parameters
fn: (...args: any[]) => T (required): The function to execute in the worker. Crucially, this function must be pure and self-contained. It cannot access any variables outside of its own scope (no closures).

fnArgs: any[] (required): An array of arguments to pass to the worker function. The hook will re-run the worker whenever the stringified version of this array changes.

Returns
An object { data, error, status }:

data?: T: The successful result returned from your function. undefined otherwise.

error?: Error: An Error object if the function throws an error. undefined otherwise.

status: 'idle' | 'running' | 'success' | 'error': The current status of the worker.