Skip to main content
Version: v3.6.0

@rooks/use-worker

Worker hook for React.


Build Status

Installation

npm install --save @rooks/use-worker

Importing the hook

import useWorker from "@rooks/use-worker"

Usage


function Demo() {
const [value, setValue] = useState(0);
const [error, setError] = useState(null);
const worker = useWorker("/worker.js", {
onMessage: e => {
console.log("message received from worker");
console.log(e.data);
setValue(e.data);
},
onMessageError: e => {
console.log(e);
}
});
return value;
}

const rootElement = document.getElementById("root");

ReactDOM.render(<Demo />, rootElement);

Arguments

ArgumentsTypeDescriptionDefault value
scriptPathstringPath to the script file that a new Worker is to be created withundefined
optionsObjectOptions object within which onMessage and onMessageError options can be passed to communicate with the worker{onMessage: () => {},,onMessageError: () => {}}

Returned Object

The worker instance is returned.