Introduction
useWorker
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
Web API
The javascript language is single-threaded, so if we're executing an expensive task, we should wait for it, before continuing to execute other portions of code. Some javascript features are offered by the browser, through the Web API (XMLHttpRequest, EventListener, Worker...). In this way, many features can be run in "parallel" without blocking our javascript code
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
- Support Transferable
the most useful feature of useWorker
, however, is the simplicity. You can see the difference between using web workers via pure javascript and via useWorker()
.
Without using useWorker
webworker.js
self.addEventListener("message", function(event) {
var numbers = [...event.data]
postMessage(numbers.sort())
});
index.js
var webworker = new Worker("./webworker.js");
webworker.postMessage([3,2,1]);
webworker.addEventListener("message", function(event) {
console.log("Message from worker:", event.data); // [1,2,3]
});
Using useWorker
index.js
const sortNumbers = numbers => ([...numbers].sort())
const [sortWorker] = useWorker(sortNumbers);
const result = await sortWorker([1,2,3])