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:
- via the DedicatedWorkerGlobalScope;
- with a blob; or
- 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: