Skip to content

Using a Blob to add a Web Worker in React

If you missed the introductory post, please start there. Otherwise...

Part of the web APIs, blobs are file-like objects of raw data and not necessarily in a JavaScript format. a Blob() constructor can accept an array, and in the below code we can see that our blob serialises a function called workerFunction into an immediately invoked function expression that is passed into our blob as the first and only element in an array. URL.createObjectURL then creates from this blob a URL which can be used to create a new Worker. From that point on we can using the worker's capacity to send and receive messages.

import { useCallback, useEffect, useMemo, useState } from "react";

export const App = () => {
  const [n, setN] = useState(0);

  setTimeout(() => setN(100 + Math.round(Math.random() * 899)), 100);

  const webWorker = (
    workerFunction: () => void,
    inputData: string,
    callback: (result: unknown) => void
  ) => {
    try {
      const code = workerFunction.toString();
      const blob = new Blob([`(${code})()`], {
        type: "text/javascript",
      });
      const workerScriptUrl = URL.createObjectURL(blob);
      const worker = new Worker(workerScriptUrl);

      worker.onmessage = (e: MessageEvent<string>) => {
        callback(e.data);
        worker.terminate();
        URL.revokeObjectURL(workerScriptUrl);
      };

      worker.postMessage(inputData);
    } catch (e: unknown) {
      console.log(e);
    }
  };

  const workerFunction = () => {
    self.onmessage = function (e: MessageEvent<string>) {
      if (e.data === "slowCalculation") {
        const result = Array(30_000_000)
          .fill(1)
          .map((value, index) => value + index)
          .reduce((total, value) => total + value);
        self.postMessage(result);
      }
    };
  };

  const memoWorkFunction = useCallback(workerFunction, [])

  const handleOnClick = () => {
    console.log("start blob worker");
    webWorker(memoWorkFunction, "slowCalculation", (result: unknown) => {
      console.log("blob worker result", result);
    });
  };

  return (
    <>
      <p>{n}</p>
      <button onClick={() => handleOnClick()}>Start web worker</button>
    </>
  );
};

export default App;

Using a blob requires a lot of boilerplate, and results in code that can be difficult to read, debug, and maintain. Use this method by all means if it suits your purpose, but there are others:

  1. via the DedicatedWorkerGlobalScope; or
  2. with the Comlink library.