search
HomeWeb Front-endJS TutorialUtilizing Web Workers for Background Processing in React Hooks Applications.

1.0 Introduction

Web Workers in React are functions that allow concurrent running of multiple threads in a React application.It enables some of the threads to run in the background, to exclude it from running as part of the main thread.

Take for example, you have an application where maybe you want to perform a complex calculation, large data fetching from an API or implementing a background notification, without altering the normal funtionality of the currently running main thread. This can be achieved by implementing React Web Hooks that ensure that the User Interface does not freeze while all these processes run in a React app.

In this guide, we will create a sample react project that implements web workers in custom react hooks to perform an exponential calculation.

Steps

Step 1: Create the React App

Create a react application.

npx create-vite myproject -- --template react

I prefer using vite to create a react app since it has a faster run time compared to create-react-app .
Here we use react as the template from vite.

Select React as your template

select JavaScript:

Select Variant as JavaScript

Utilizing Web Workers for Background Processing in React Hooks Applications.

open the project on an editor. (I'll use Vs code for this project)

code .

Step 2: Scaffolding our project.

Inside the src directory, create another directory hooks/useWebWorkers.
Inside this folder, create an index.js file that will hold our web worker as shown below:

Utilizing Web Workers for Background Processing in React Hooks Applications.

Step 3: Creating our web worker

Inside our /hooks/useWebWorker/index.js, we create a custom hook, that creates our web worker

Create a useWebWorker custom hook that takes workerFunction and inputData as parameters.

const useWebWorker =(workerFunction,inputData)=>{

}
export default useWebWorker;

Initialize states for our result,error and status of our web worker using useState hook.

import {useState} from 'react'
const useWebWorker =(workerFunction,inputData)=>{
const [result,setResult] = useState(null);
const [error,setError] = useState(null);
const [loading,setLoading] = useState(false);

}
export default useWebWorker;

i) result stores the result of our web worker. Initially set to null.

ii)error keeps track of the error that may occur in the web worker.Initially set to null.

iii) loading gives state of our web worker whether it's processing data or not.Initially set to false.

Initialize a useEffect to hold our web worker.

import {useState,useEffect} from 'react'
const useWebWorker =(workerFunction,inputData)=>{
const [result,setResult] = useState(null);
const [error,setError] = useState(null);
const [loading,setLoading] = useState(false);

useEffect(()=>{

},[inputData])

}
export default useWebWorker;

The useEffect hook runs whenever inputData changes, because it has been set as a delimiter,
When the inputData is null or undefined, the hook exits early.

if(!inputData)return;

Ensure that all the states are correctly reset

    setLoading(true);
    setError(null);
    setResult(null);

Create a web worker blob

    const blob = new Blob(
      [
        `
          self.onmessage = function(event) {
            (${workerFunction.toString()})(event);
          };
        `,
      ],
      { type: "application/javascript" }
    );

Converts workerFunction to a string and includes it in a Blob object.This Blob represents the JavaScript code that will run in the Web Worker.

Create a Worker that generates a URL for the Blob and creates a new Web Worker using this URL:

    const workerScriptUrl = URL.createObjectURL(blob);
    const worker = new Worker(workerScriptUrl);

Set up an event handler for the message emitted by the worker.

worker.onmessage(event){

}

when the web worker sends a message to the main thread (using postMessage), the event handler is triggered.
event.data contains either valid result or error in the web worker. We handle rendering of either the error or valid results inside the if-else statements.

In case of an error, we set the error to event.data.error inside setError().
if valid results are returned, we pass the result to event.data inside the setResult()

    worker.onmessage = (event) => {
      console.log("Worker result:", event.data);
      if (event.data.error) {
        setError(event.data.error);
      } else {
        setResult(event.data);
      }
      setLoading(false);
    };

Sets loading to false when done.

Handle Web worker errors:

We use worker.onerror(event){

}
We pass event as a parameter,update the error to event.message and update loading state to false.

    worker.onerror = (event) => {
      console.error("Worker error:", event.message);
      setError(event.message);
      setLoading(false);
    };

We now send the inputData to the web worker

worker.postMessage(inputData);

We terminate the Web Worker and revoke the Blob URL when the component unmounts or inputData or workerFunction changes:

    return () => {
      worker.terminate();
      URL.revokeObjectURL(workerScriptUrl);
    };
  }, [inputData, workerFunction]);

We finally return the state of the web worker by returning result,error and loading states:

return {result,error,loading}

Export the useWebWorker:

export default useWebWorker;

Below is the complete code for hooks/useWebWorker/index.js:

import { useState, useEffect } from "react";

const useWebWorker = (workerFunction, inputData) => {
  const [result, setResult] = useState(null);
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (!inputData) return;

    setLoading(true);
    setError(null);
    setResult(null);

    const blob = new Blob(
      [
        `
          self.onmessage = function(event) {
            (${workerFunction})(event);
          };
        `,
      ],
      { type: "application/javascript" }
    );

    const workerScriptUrl = URL.createObjectURL(blob);
    const worker = new Worker(workerScriptUrl);

    worker.onmessage = (event) => {
      console.log("Worker result:", event.data);
      setResult(event.data);
      setLoading(false);
    };

    worker.onerror = (event) => {
      console.error("Worker error:", event.message);
      setError(event.message);
      setLoading(false);
    };

    console.log("Posting message to worker:", inputData);
    worker.postMessage(inputData);

    return () => {
      worker.terminate();
      URL.revokeObjectURL(workerScriptUrl);
    };
  }, [inputData, workerFunction]);

  return { result, error, loading };
};

export default useWebWorker;

Step 4: Editing our App.jsx

In our App.jsx, let's define a worker function that will be executed by our web worker:

const workerFunction = (e) => {
  const { base, exponent } = e.data;
  console.log("Worker function received data:", base, exponent);

  let result = 1;
  for (let i = 0; i 



<p>e.data contains data from the web worker.</p>

<blockquote>
<p>The workerFunction:<br>
Logs the received data (base and exponent).<br>
Computes the power of base raised to exponent.<br>
Sends the result back to the main thread using self.postMessage(result).</p>
</blockquote>

<p>Let's now define our App functional component inside our App.jsx:<br>
</p>

<pre class="brush:php;toolbar:false">const App = () => {
  const [base, setBase] = useState("");
  const [exponent, setExponent] = useState("");
  const [inputData, setInputData] = useState(null);
  const { result, error, loading } = useWebWorker(workerFunction, inputData);

base: Stores the base number input.
exponent: Stores the exponent number input.
inputData: Stores the data to be sent to the worker.
Custom Hook Usage: useWebWorker is used to create a Web Worker and manage its state.

  const handleBaseChange = (e) => setBase(e.target.value);
  const handleExponentChange = (e) => setExponent(e.target.value);

handleBaseChange: Updates base state when the input value changes.
handleExponentChange: Updates exponent state when the input value changes

  const handleCalculate = () => {
    setInputData({ base: Number(base), exponent: Number(exponent) });
  };

handleCalculate Function: Converts base and exponent to numbers and sets them as inputData for the Web Worker.

  return (
    <div>
      <h1 id="Exponential-Calculation-with-Web-Worker">Exponential Calculation with Web Worker</h1>
      <div>
        <label>
          Base:
          <input type="number" value="{base}" onchange="{handleBaseChange}">
        </label>
      </div>
      <div>
        <label>
          Exponent:
          <input type="number" value="{exponent}" onchange="{handleExponentChange}">
        </label>
      </div>
      <button onclick="{handleCalculate}">Calculate</button>
      {loading && <div>Loading...</div>}
      {error && <div>Error: {error}</div>}
      {!loading && !error && result !== null && <div>Result: {result}</div>}
    </div>
  );
};

JSX Layout:
Displays a title and input fields for base and exponent.
A button triggers the handleCalculate function.
Conditionally renders loading, error, or result messages based on the state.

Below is the complete App.jsx code:

import { useState } from "react";
import useWebWorker from "./hooks/useWebWorker";
import "./App.css";

const workerFunction = (e) => {
  const { base, exponent } = e.data;
  console.log("Worker function received data:", base, exponent);

  let result = 1;
  for (let i = 0; i  {
  const [base, setBase] = useState("");
  const [exponent, setExponent] = useState("");
  const [inputData, setInputData] = useState(null);
  const { result, error, loading } = useWebWorker(workerFunction, inputData);

  const handleBaseChange = (e) => setBase(e.target.value);
  const handleExponentChange = (e) => setExponent(e.target.value);

  const handleCalculate = () => {
    setInputData({ base: Number(base), exponent: Number(exponent) });
  };

  return (
    <div>
      <h1 id="Exponential-Calculation-with-Web-Worker">Exponential Calculation with Web Worker</h1>
      <div>
        <label>
          Base:
          <input type="number" value="{base}" onchange="{handleBaseChange}">
        </label>
      </div>
      <div>
        <label>
          Exponent:
          <input type="number" value="{exponent}" onchange="{handleExponentChange}">
        </label>
      </div>
      <button onclick="{handleCalculate}">Calculate</button>
      {loading && <div>Loading...</div>}
      {error && <div>Error: {error}</div>}
      {!loading && !error && result !== null && <div>Result: {result}</div>}
    </div>
  );
};

export default App;

We can now use npm run dev to view our project.
Below is a live preview of our project:
Web Workers Project Implementation

Conclusion

Implementing Web Workers in your React applications can significantly enhance performance, especially when dealing with CPU-intensive tasks. By offloading such tasks to background threads, you ensure that your app remains responsive and provides a smooth user experience.

In our example, we've seen how straightforward it can be to set up and use Web Workers in a React environment. From dynamically creating a worker using a custom hook to managing the communication between the main thread and the worker, every step is designed to be both efficient and easy to integrate.

This approach not only helps in maintaining a responsive UI but also makes your app more robust and user-friendly. Whether it's for complex calculations, data processing, or any other heavy lifting, Web Workers can be your go-to solution for multitasking in modern web applications.

Remember, the key to a great user experience is not just about what your app does but how it feels while doing it. By implementing Web Workers, you can ensure that your app feels snappy and responsive, keeping your users happy and engaged. So, go ahead and explore the power of Web Workers in your next React project – your users will thank you for it!

The above is the detailed content of Utilizing Web Workers for Background Processing in React Hooks Applications.. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use