Skip to content

Vite is designed for front-end React development, so the notion of Node.js' process module doesn't really apply. How then does one create and access process.env environment variables? Thankfully it's surprisingly straightforward. Firstly create a .env file in your project root and put, say, the following into it:

BASE_URL = https://some.url.here

Then you can access that via Vite's own env variables object import.meta.env:

...
const url = import.meta.env.BASE_URL
...

Except that will not work. Here url will be undefined. To ensure that Vite collects and env variables meant for it, prefix your var names with VITE_:

VITE_BASE_URL = https://some.url.here
...
const url = import.meta.env.VITE_BASE_URL
...

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

Why write loads of boilerplate when there are third-party libraries you can just plug in? Well there are reasons of course, but perhaps in your case they are not compelling enough, and the simplicity of a library appeals. If so, you can use comlink. Install it.

npm i comlink

Or the equivalent in yarn. Then, if you are using Vite like me.

npm i -D vite-plugin-comlink

Or the equi... Then configure Vite to use the plugin.

import { defineConfig } from "vite";
import { comlink } from "vite-plugin-comlink";

import react from "@vitejs/plugin-react";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react(), comlink()],
  worker: {
    plugins: () => comlink(),
  },
});
/// <reference types="vite/client" />
/// <reference types="vite-plugin-comlink/client" />

And you are good to go. Back in your workers directory create a new file called comlink-worker.ts to hold our slow calculation.

export const slowCalculation = () => {
  const result = new Array<number>(30_000_000)
    .fill(0)
    .map((value, index) => value + index)
    .reduce((total, value) => total + value, 0);
  return result;
};

And thanks to the magic of other people's coad, the amount you have to write to run it is minimal.

import { useState } from "react";

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

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

  const workerInstance = new ComlinkWorker<
    typeof import("./workers/comlink-worker")
  >(new URL("./workers/comlink-worker", import.meta.url));

  const handleOnClick = async () => {
    console.log("start comlink worker");
    const result = await workerInstance.slowCalculation();
    console.log("comlink worker result", result);
  };

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

export default App;

There are other ways to run a web worker in React

  1. via the DedicatedWorkerGlobalScope; or
  2. with a blob.

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.

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

In your src directory create a workers directory and within that a file called worker.ts.

self.onmessage = (e: MessageEvent<string>) => {
  if (e.data === "slowCalculation") {
    const result = Array(30_000_000)
      .fill(1)
      .map((v, i) => v + i)
      .reduce((t, v) => t + v);
    self.postMessage(result);
  }
};

Web workers communicate via messages. Here, the DedicatedWorkerGlobalScope is using its onmessage handler to listen for messages from individual web workers elsewhere via the self keyword, because self is the global worker scope. In this case, if the worker in question has requested a slow calculation, it performs exactly that, and returns the result.

Our app component now needs to request that response from self.

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

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

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

  const worker: Worker = useMemo(
    () => new Worker(new URL("./workers/worker.ts", import.meta.url)),
    []
  );

  const handleOnClick = () => {
    console.log("start web worker");
    worker.postMessage("slowCalculation");
  };

  useEffect(() => {
    if (window.Worker) {
      worker.onmessage = (e: MessageEvent<object[]>) => {
        console.log("web worker result", e.data);
        worker.terminate();
      };
    }
  }, [worker]);

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

export default App;

This is the code from our introductory post with some additions

  1. a worker (created here in the recommended way from the Vite docs) which references our worker.ts file;
  2. a useEffect hook to handle results from our web worker via worker.onmessage; and
  3. an onClick handler to start the web worker.

Now we see that when the slow calculation is farmed out to the global worker scope, the UI is able to continue rendering in the meanwhile.

This is one way to implement a web worker in React, but there are others:

  1. with a blob; or
  2. with the Comlink library.

Part 1: Introduction

Given that JavaScript is single-threaded, how does one run a processor-intensive script without locking up the UI? With something called a Web Worker. which runs in a separate context to the current window. Like any JavaScript app, React apps can utilise web workers, and there are several ways of doing it. I will show you three different ways, so you can choose which is best for you:

  1. via the DedicatedWorkerGlobalScope;
  2. with a blob; or
  3. with the Comlink library.

Firstly create your own React spike, by whatever means suits you, create-react-app or Vite, or something else. Call it whatever you want. If it matters: I used Vite and called it web-worker. You will need your root app component plus whatever supports it. For me that App.tsx and these files:

index.html
main.tsx
index.css
(and App.tsx)

The first three look like this:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Three methods of running Web Workers in React</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.tsx"></script>
  </body>
</html>
import "./index.css";

import React from "react";
import ReactDOM from "react-dom/client";

import App from "./App.tsx";

ReactDOM.createRoot(document.getElementById("root")!).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);
#root {
  margin: 0 auto;
}

body {
  margin: 0;
  padding: 20px;
}

Our web worker will run a background process that will not render anything to the screen, but we will put something on the screen to visualise it blocking the thread: a setTimeout function which will render a random integer to the screen ten times a second.

import { useState } from "react";

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

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

  return (
    <>
      <p>{n}</p>
    </>
  );
};

export default App;

Next lets add a button which, when clicked, will run a slow calculation.

import { useState } from "react";

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

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

  const slowCalculation = () => {
    const result = Array(30_000_000)
      .fill(1)
      .map((value, index) => value + index)
      .reduce((total, value) => total + value);
    self.postMessage(result);
  };

  return (
    <>
      <p>{n}</p>
      <button
        onClick={() => {
          console.log("start slow calculation...");
          const result = slowCalculation();
          console.log("slow calculation result:", result);
        }}
      >
        Press
      </button>
    </>
  );
};

export default App;

When clicked, slowCalculation hogs the processor and prevents setTimeout from updating the value of n. Clearly this is *cough* 'suboptimal.'

This is where a web worker can help, by farming that intensive process outside of the single Javascript thread. Now let's look at three ways of doing this:

  1. via the DedicatedWorkerGlobalScope;
  2. with a blob; or
  3. with the Comlink library.