A Step-by-Step Guide on Web Workers using React

Table of Contents

To understand the Web Workers and the problem they are designed for, you need to understand how JavaScript code is executed at runtime. At the time of execution, the JavaScript code is executed in a sequential manner. As soon as a piece of code is executed, the next piece of code in the line starts executing, and so forth.

JavaScript is a common alternative to use with many other languages while custom software development. And that is the reason it is booming constantly.

From a technical perspective, we say that JavaScript is single-threaded. This behavior implies that once a piece of code is executed, any subsequent code must wait for the execution of the previous code.

Thus, every line of code “blocks” the execution of everything else that follows it. It is therefore desirable that each piece of code terminates as rapidly as possible.

If any of the code takes a long time to execute, our program ceases to work. It appears as a frozen, non-responsive page in the browser. In extreme circumstances, the card freezes completely.

Imagine driving in a lane. If one of the drivers ahead stops moving for any reason, you’ll face a traffic jam. With a program such as Java, the flow like the traffic may continue other lanes i.e., routes. Thus, Java is said to be multi-threaded. Web Workers is an effort to bring multi-threaded behavior to JavaScript.

What is Web Worker?

A web worker is a JavaScript script that is executed independently in the background. Web workers can often use more than one CPU. A thread worker can carry out the tasks without interfering with the user interface.

Additionally, they can perform I/O using XMLHttpRequest (although the responseXML and channel attributes are always null) or fetching (without such restrictions).

Once created, the worker can send messages to the JavaScript code that created it by sending messages to the event manager specified by that code (and conversely).

READ ALSO:  Hiring Freelance React Js Developer Vs Hiring a React Js Development Company

Practical for Web Worker

In this practice, we will build a loop executer for num. We’ll pass the number in the input field and on the button click we must iterate the loop. On the iteration, we will display the message indicating how many numbers are loaded on the page.

Web Workers is an attempt to introduce the multi-threaded behavior in JavaScript.

App.js

import React from ‘react’

import { Component } from ‘react’

class App extends Component {

  constructor() {

    super()

    this.state = {

      num: ”,

      result: ”,

      loadingMessage: ”

    }

    this.handleCount = this.handleCount.bind(this)

    this.handleCalculate = this.handleCalculate.bind(this)

  }

  handleCount(e) {

    this.setState({

      num: e.target.value

    })

  }

  handleCalculate() {

    const { num } = this.state

    let result = 0;

    for (let i = 1; i <= num; i++) {

      this.setState({

        loadingMessage: `Loaded ${i} / ${num}`

      })

      for (let j = 0; j < i; j++) {

        result++

      }

    }

    this.setState({

      result

    })

  }

  render() {

    return (

      <div>

        <input type=’number’ value={this.state.num} onChange={this.handleCount} />

        <br /> <br />

        <button onClick={this.handleCalculate}>Calculate</button>

        <h1>{this.state.loadingMessage}</h1>

        <h1>{this.state.result}</h1>

      </div>

    )

  }

}

export default App

Here, we took the input box number and a “loadingMessage” state to display the numbers which are already loaded. Whenever we enter a short range that time it will display normally without stopping page UI. Below are the results:

Graphical user interface, text, application, chat or text message

Description automatically generated

Figure 1. Short Range Number

But when we input a long value to iterate the loop at that time, it will block the UI of the page. And after a while, the page will not respond. Here, we have entered 500000000 in the input box, after some time it will display the unresponsive page option. The output is shown below.

READ ALSO:  Attributes of Clipping Path Service for Graphic Designers
word image 29052 2

Figure 2. Long Range Number

Now, we will perform the same task using the web worker.

App.js

import React from ‘react’

import { Component } from ‘react’

import workerScript from ‘./Worker’

import React from ‘react’

import { Component } from ‘react’

import workerScript from ‘./Worker’

class App extends Component {

  constructor() {

    super()

    this.state = {

      num: ”,

      result: ”,

      loadingMessage: ”

    }

    this.handleCount = this.handleCount.bind(this)

    this.handleCalculate = this.handleCalculate.bind(this)

  }

  componentDidMount() {

    this.worker = new Worker(workerScript)

    this.worker.addEventListener(‘message’, e => {

      const type = e.data.type;

      if (type === ‘loading’) {

        const { i, num } = e.data;

        this.setState({

          loadingMessage: `Loaded ${i} / ${num}`

        })

      }

      else {

        const { result } = e.data;

        this.setState({

          result

        })

      }

    })

  }

  handleCount(e) {

    this.setState({

      num: e.target.value

    })

  }

  handleCalculate() {

    const { num } = this.state

    this.worker.postMessage(num)

  }

  render() {

    return (

      <div>

        <input type=’number’ value={this.state.num} onChange={this.handleCount} />

        <br /> <br />

        <button onClick={this.handleCalculate}>Calculate</button>

        <h1>{this.state.loadingMessage}</h1>

        <h1>{this.state.result}</h1>

      </div>

    )

  }

}

export default App

In the App.js component, we have imported the worker component. In the handleCalculate function, we have passed the integer “num” as a parameter in the worker.js file. We will write the same logic as of before the worker in the Worker.js file on its button click event.

READ ALSO:  Find Out the Best Logo Makers to Create a Free Logo

Worker.js

const loopworker = () => {

    onmessage = (e) => {

        const num = e.data;

        let result = 0;

        for (let i = 1; i <= num; i++) {

            const data = { type: ‘loading’, i, num }

            postMessage(JSON.parse(JSON.stringify(data)))

            for (let j = 0; j < i; j++) {

                result++;

            }

        }

        const data = {

            type: ‘result’,

            result

        }

        postMessage(JSON.parse(JSON.stringify(data)))

    }

}

let code = loopworker.toString()

code = code.substring(code.indexOf(“{“) + 1, code.lastIndexOf(“}”))

const blob = new Blob([code], { type: ‘application/javascriptssky’ })

const workerScript = URL.createObjectURL(blob)

module.exports = workerScript;

Let’s understand the above.

Self:

Here, self is guaranteed to point to a ServiceWorkerGlobalScope in which you can find properties such as clients, registrations or caches, and various event handlers. On the other hand, it follows the same dynamic binding rules as the rest of the JavaScript environment. It doesn’t matter that you always remember it, but the advice is to use self when you want to specifically refer to the global context.

e.data:

The values we are passing from App.js component we will get in the “e.data” object.

PostMessage:

Using postMessage we can communicate with workers present in the Worker.js component.

Conclusion: 

Web Worker in React is a significant topic for React developers, which gives the idea that how to execute multi-thread programs. It is the gateway for any business to acquire a customer and leads. Therefore, keeping a primary focus on user requirements is essential. Here, in this blog, we have learned about what is web worker and we have seen the practical with the worker.