A react custom hook to deal with webworkers
npm install react-webworker-hook
npm install --save react-webworker-hook
`
$3
a quick sample here https://codesandbox.io/p/sandbox/react-webworker-hook-example-6xt8rm
`js
import React, { useState } from "react";
import useWebWorker from "react-webworker-hook";
function GenerateFibonacci() {
const [data = 0, postData] = useWebWorker({
url: "./webworker_example.js"
});
const [count, setCount] = useState(0);
return (
{fibonacci for ${count}: ${data}}
onClick={() => {
setCount(count + 1);
postData(count);
}}
>
Generate
);
}
export default GenerateFibonacci;
`
It also comes with other helper functions like
when we have a small script which should be deployed into webworker
`js
const [data, postData, error] = useWebWorkerFromScript(
)
`
pass url of a web worker, webworker should be served from the same origin
`js
const [data, postData, error] = useWebWorkerFromUrl('./webworker_example.js');
`
when we have an existing worker and it should be used through hook
`js
const [data, postData, error] = useWebWorkerFromWorker('./webworker_example.js');
`
API
$3
a config object with either url or worker object
$3
- data - data which has been sent by webworker
- postMessage - handler which is used to communicatew with webworker
- error` - which will contain an error object if thrown by web worker