By using this site, you agree to the Privacy Policy and Terms of Use.
Accept
The Digital TechnologyThe Digital Technology
  • Home
  • Digital Marketing
    • SEO
    • PPC
    • Blogging
    • Social Media
  • Tech
    • Artificial Intelligence
    • Blockchain
    • Cyber Security
  • Business Ideas
    • Entrepreneurs
      • Startup
    • Success Stories
  • Internet
    • Software
    • Apps
    • Web Design and Development
  • Gadgets
    • Computers
    • Smartphone
      • Android
      • iOs
  • How To
  • Make Money Online
Search
  • Contact
  • Blog
  • Complaint
  • Advertise
© 2022 Foxiz News Network. Ruby Design Company. All Rights Reserved.
Reading: A Step-by-Step Guide on Web Workers using React
Share
Notification Show More
Latest News
Career Paths
The Most Interesting Career Paths in 3D Printing
Technology
VoIP Solutions 
Top 7 Reasons To Switch To VoIP Solutions
Phones & Tech
Instagram Story Viewer
What is Instagram Story Viewer Order?
Social Media Instagram
Power surges
Tips for Protecting Your Electronics from Power Surges
Technology
White Label VPN
Benefits of White Label VPN Solution
VPN
Aa
The Digital TechnologyThe Digital Technology
Aa
  • Home
  • Digital Marketing
  • Tech
  • Business Ideas
  • Internet
  • Gadgets
  • How To
  • Make Money Online
Search
  • Home
  • Digital Marketing
    • SEO
    • PPC
    • Blogging
    • Social Media
  • Tech
    • Artificial Intelligence
    • Blockchain
    • Cyber Security
  • Business Ideas
    • Entrepreneurs
    • Success Stories
  • Internet
    • Software
    • Apps
    • Web Design and Development
  • Gadgets
    • Computers
    • Smartphone
  • How To
  • Make Money Online
Follow US
  • Contact
  • Blog
  • Complaint
  • Advertise
© 2022 Foxiz News Network. Ruby Design Company. All Rights Reserved.
The Digital Technology > Blog > Web Design and Development > A Step-by-Step Guide on Web Workers using React
Web Design and Development

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

Vinod Satapara
Last updated: 2023/02/26 at 3:37 PM
Vinod Satapara
Share
Web workers
Web workers
SHARE

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

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.

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.

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.

You Might Also Like

The Future of Web Design: Combining AR and VR for Ultimate User Experience

Tips for Constructing Viable Big Data Projects

Top 8 Flutter Benefits to Use Flutter Development Company

10 Strategies for Making Your Mobile App Stand Out in a Crowded Market

Top 5 Programming Languages to Mention in Your 2023’s Learning List

TAGGED: web design and development, Web workers, Web workers using react

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share this Article
Facebook Twitter Copy Link Print
Share
By Vinod Satapara
Follow:
Technocrat and entrepreneur of a reputed Angular development company with years of experience in building large-scale enterprise web, cloud, and mobile applications using the latest technologies like ASP.NET, CORE, .NET MVC, Angular, and Blockchain. Keen interest in addressing business problems using the latest technologies and helping the organization to achieve goals.
Previous Article Metaverse The Benefits to Implement Metaverse in University for Students
Next Article Blockchain Technology for business Benefits of Blockchain Technology for Business Growth

Stay Connected

14 Like
10 Follow
24 Pin
54 Follow

Top Categories

  • Business Ideas
  • Digital Marketing
  • How To
  • Internet
  • Blockchain
  • Technology
//

The Digital Technology is world’s leading online platform for publishing the latest news on digital marketing, technology, software, business, and more.

Quick Link

  • About Us
  • Contact Us
  • Privacy & Policy
  • Write For Us

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

The Digital TechnologyThe Digital Technology
Follow US

© 2023. The Digital Technology. All Rights Reserved.

Join Us!

Subscribe to our newsletter and never miss our latest news, podcasts etc..

Zero spam, Unsubscribe at any time.

Removed from reading list

Undo
Welcome Back!

Sign in to your account

Lost your password?