$ npm install @koale/useworker
3KB
!npm install --save @koale/useworker
import { useWorker, WORKER_STATUS } from "@koale/useworker";
Before you start using this hook, I suggest you to read the Web Worker documentation.
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>
);
};
More examples: https://github.com/alewin/useWorker/tree/develop/example
useWorker
functionuseWorker
function #37Most react projects are initialized through Create React App. CRA unfortunately does not offer support for webworkers, unless you eject and change the webpack configuration manually.
This library allows you to use web workers without having to change the CRA configuration, which is why there are often limitations or particular workarounds.
If you are interested in changing the webpack configuration to manually manage your workers, see: worker-loader
--
There's a known issue related to transpiling tools such as Babel causing Not refereced
errors.
Since the approach of this library is moving the entire function passed to the Hook to a worker, if the function gets transpiled, variable definitions used by the transpiling tool may get out of scope when the function gets moved to the worker, causing unexpected reference errors.
If you're experimenting this type of issue, one workaround is wrapping your function declaration inside a function object as a string.
const sum = new Function(`a`, `b`, `return a + b`)
The library is experimental so if you find a bug or would like to request a new feature, open an issue
MIT © alewin
© 2010 - cnpmjs.org x YWFE | Home | YWFE