Create Web Worker in React Typescript
Question:
How to create Web Worker in React Typescript? Answer:
const myWorker = new Worker(
new URL("./webWorkers/timerWorker.ts", import.meta.url)
);
Description:
To create a web worker you need to use the Worker
constructor and specify the location of the script you want to execute in the worker thread. It sounds simple, but how can we do it in a TypeScript-based React application?
From Webpack 5 you can use Web Workers without any additional library (like worker-loader
).
Follow the following steps to integrate a simple web worker into your project:
- Create a
ts
file for your worker code. In this example, I have created awebWorkers
folder and put atimerWorker.ts
file inside it. The folder structure looks like this: - In the web worker (
timerWorker.ts
) I simply start an interval timer that sends a message in every seconds:
setInterval(function () { postMessage("Send message from worker"); }, 1000); export {};
- In the main application (
App.tsx
) - or in a component where you want to use WebWorkers - create aWorker
that uses thetimerWorker.ts
. Note how I import the file using theURL
constructor and theimport.meta.url
built-in property.
const myWorker = new Worker( new URL("./webWorkers/timerWorker.ts", import.meta.url) );
- Finally, add message listeners to the worker and put the code inside a
useEffect
hook that creates the worker only once when the component is first rendered and removes it when the component is removed:
useEffect(() => { const myWorker = new Worker( new URL("./webWorkers/timerWorker.ts", import.meta.url) ); myWorker.onmessage = function (msg) { console.log("Message received from myWorker: ", msg); setTime(new Date().toLocaleTimeString()); }; return () => { console.log("Terminate web worker"); myWorker.terminate(); }; }, []);
During build time webpack compiles the timerWorker.ts
into a separate js
file that will be loaded by the Worker
constructor inside the main app bundle.
Reference:
MDN Web Workers reference
Share "How to create Web Worker in React Typescript?"
Related snippets:
Tags:
create, use, web worker, react, useeffect, typescript Technical term:
Create Web Worker in React Typescript