useWorker()
is a js library (with typescript support) that allows you to use the Web Worker Web API, through React Hooks. This library allows you to run the expensive function without blocking the user interface, using a simple syntax that makes use ofPromise
import React from "react";
import { useWorker, WORKER_STATUS } from "@koale/useworker";
const numbers = [...Array(5000000)].map(e => ~~(Math.random() * 1000000));
const sortNumbers = nums => nums.sort();
const Example = () => {
const [sortWorker, { status, kill }] = 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>);
};
Installation per NPM/Yarn:
npm install --save @koale/useworker
useWorker()
→useWorker()
Source (GitHub) →
🤔 Unfamiliar with Web Workers? Check out Handling JavaScript events with Web Workers then!