/ Hooks

A React Hook for Blocking-Free Background Tasks

A React Hook for Blocking-Free Background Tasks

useWorker

Use web workers with react hook.

๐ŸŽจ Features

  • Run expensive function without blocking UI (Show live gif)
  • Supports Promises pattern instead of event-messages
  • Size: less than 3KB!
  • Clear API using hook
  • Typescript support
  • Garbage collector web worker instance
  • Remote dependencies option
  • timeout option

๐Ÿ’พ Install

  • @latest
npm install --save @koale/useworker

๐Ÿ”จ Import

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

๐Ÿพ 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

  • [x] Kill Web Worker
  • [x] Reactive web worker status
  • [x] Add timeout option
  • [x] import and use remote script inside useWorker function
  • [ ] support Transferable Objects #47
  • [ ] import and use local script inside useWorker function #37
  • [ ] useWorkers Hook #38

GitHub

Comments