SoFunction
Updated on 2025-03-02

Detailed explanation of how to integrate and use web worker in React projects

introduction

In complex React applications, some compute-intensive or time-consuming operations may block the main thread, resulting in stuttering or slow response in the user interface. To optimize the user experience, Web Worker can be used to perform these operations in the background thread, so as not to affect the operation of the main thread. This article will explain in detail how to integrate and use Web Worker in React projects to improve application performance.

Initialize React project and directory structure adjustment

Use CRA to create a new React project using TypeScript:

npx create-react-app testworker --template=typescript

After that, adjust the project structure appropriately to support the use of Web Worker. Specifically add:

  • src/workers/: Store script code for Web Worker.
  • src/data/: Store holiday data.

Revise

Modify the project root directoryFile and adapt to Web Worker.

Import the required files for the application

Import the scripts and fake data needed to create a Web Worker from a local file:

import React from 'react';
import './';
import workerScript from './workers/';
import testData from './data/';

Implement App Components

existAppIn the component, implement a callback function for a button click event, which will start a Web Worker instance and communicate with it through messaging:

function App() {
  const handleButtonClick = () => {
    const workerInstance = new Worker(workerScript);

     = function(event: MessageEvent) {
      const { data } = event;
      ('Received data from worker: ', data);
    };

    ({
      msg: 'parse it',
      payload: (testData)
    });
  };

  return (
    <div className="App">
      <header className="App-header">
        <button onClick={handleButtonClick}>
          Click to Load Worker
        </button>
      </header>
    </div>
  );
}

export default App;

The above code is fromsrc/workers/The imported script passesWorkerThe constructor creates a Web Worker instance. Then set the instanceonmessageEvent callback function to process data when a message from Worker is received. Finally, after clicking the buttonpostMessageMethod sends processing request to Worker.

Create a Web Worker script

existsrc/workersCreated in the directoryFiles to implement the logic of Web Worker

const workerCode = () => {
  // Listen to message from the main thread
   = function (event) {
    const { data } = event;
    ('Data received by worker: ', data);
    if (data) {
      const { msg, payload } = data;
      let reply, result, startTime, endTime;
      if (msg === 'parse it') {
        reply = 'parsed';
        startTime = new Date().getTime();
        result = (payload);
        endTime = new Date().getTime();
      }
      ({ msg: reply, payload: result, cost: endTime - startTime });
    }
  };
};

let code = ();
code = (('{') + 1, ('}'));
const blob = new Blob([code], { type: 'application/javascript' });
const workerScriptURL = (blob);

export default workerScriptURL;

existworkerCodeIn the function, it is defined for Web WorkeronmessageEvent handler function to receive messages from the main thread. When a message from the main thread is received, this code performs data analysis and other operations based on the message content and calculates the execution time. Then passpostMessageReturn the result to the main thread.

In order toworkerCodeThe function is converted into aWorkerThe URL used by the constructor, converts the function into a string, and extracts the function body from it. Next, use this function body content to create aBlobobject, and passCreate a URL to the blob.

Edit fake data files

existsrc/dataCreate a directory calledfile that contains data for testing.

{
  "name": "example-package",
  "version": "1.0.0",
  "description": "An example package for testing Web Worker.",
  "keywords": ["react", "webworker", "testing"],
  //... other  properties
}

The content here can also be changed to other complex JSON data to test the performance of Web Worker when processing large-scale datasets.

run

After completing the above steps, the React project has integrated the Web Worker. After the user clicks the button on the interface, the main thread will send a processing request to the Web Worker. After receiving the message, the Web Worker performs time-consuming operations in the background and returns the result to the main thread.

The above is a detailed explanation of how to integrate and use web workers in React projects. For more information about React integration and use web workers, please follow my other related articles!