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