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
- a worker (created here in the recommended way from the Vite docs) which references our
worker.tsfile; - a
useEffecthook to handle results from our web worker viaworker.onmessage; and - an
onClickhandler 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: