/useWorker

⚛️ useWorker() Hook: Running heavy task in background, without blocking the UI

Primary LanguageJavaScriptMIT LicenseMIT


useWorker

Use web workers with react hook
https://useworker.js.org/
Tweet

GitHub size GitHub TypeScript Support


🎨 Features

  • Run expensive function without blocking UI (Show live gif)
  • Supports Promises pattern instead of event-messages
  • Size: < 1KB, with zero dependencies
  • Clear API using hook
  • Typescript support
  • Garbage collector web worker instance
  • timeout option

💾 Install

npm install --save @koale/useworker

🔨 Import

import { useWorker, WORKER_STATUS } from "@koale/useworker";

📙 Documents


🍞 Demo


⚙ Web Workers

Before you start using this hook, I suggest you to read the Web Worker documentation.


🐾 Usage

import React from "react";
import { useWorker } from "@koale/useworker";

const numbers = [...Array(5000000)].map(e => ~~(Math.random() * 1000000));
const sortNumbers = nums => nums.sort();

const Example = () => {
  const [sortWorker] = useWorker(sortNumbers);

  const runSort = async () => {
    const result = await sortWorker(numbers); // non-blocking UI
    console.log("End.");
  };

  return (
    <button type="button" onClick={runSort}>
      Run Sort
    </button>
  );
};

🐾 Examples

Edit white-glitter-icji4

More examples: https://github.com/alewin/useWorker/tree/develop/example


🔧 Roadmap

  • Kill Web Worker
  • Reactive web worker status
  • Add timeout option
  • import and use external script inside useWorker function
  • import and use local script inside useWorker function
  • run multiple instance of the worker

🌏 Contribute? Bug? New Feature?

The library is experimental so if you find a bug or would like to request a new feature, open an issue


💡 Similar Project


📜 License

MIT © alewin


Netlify Status