- Instant help with your JavaScript coding problems

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:

  1. Create a ts file for your worker code. In this example, I have created a webWorkers folder and put a timerWorker.ts file inside it. The folder structure looks like this:

    WebWorker directory structure in React

  2. 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 {};​


  3. In the main application (App.tsx ) - or in a component where you want to use WebWorkers - create a Worker that uses the timerWorker.ts . Note how I import the file using the URL constructor and the import.meta.url built-in property.

    const myWorker = new Worker(
      new URL("./webWorkers/timerWorker.ts", import.meta.url)
    );​


  4. 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.

 

Share "How to create Web Worker in React Typescript?"
Tags:
create, use, web worker, react, useeffect, typescript
Technical term:
Create Web Worker in React Typescript