useWorker() – Use Web Workers with React Hooks

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 of Promise

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!

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.