@rooks/use-worker

A React Hooks package for worker

Usage no npm install needed!

<script type="module">
  import rooksUseWorker from 'https://cdn.skypack.dev/@rooks/use-worker';
</script>

README

@rooks/use-worker

Note: Future updates to this package have moved to the main package rooks. All hooks now reside in a single package which you can install using

npm install rooks

or

yarn add rooks

Rooks is completely treeshakeable and if you use only 1 of the 50+ hooks in the package, only that hook will be bundled with your code. Your bundle will only contain the hooks that you need. Cheers!

TitleCard

Build Status

About

Worker hook for React.

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

Arguments Type Description Default value
scriptPath string Path to the script file that a new Worker is to be created with undefined
options Object Options object within which onMessage and onMessageError options can be passed to communicate with the worker {onMessage: () => {},,onMessageError: () => {}}

Returned Object

The worker instance is returned.