首页 > web前端 > js教程 > 正文

在 React Hooks 应用程序中利用 Web Worker 进行后台处理。

WBOY
发布: 2024-07-24 21:09:51
原创
869 人浏览过

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 < exponent; i++) {
    result *= base;
  }

  self.postMessage(result);
};
登录后复制

e.data contains data from the web worker.

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

Let's now define our App functional component inside our App.jsx:

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 (
    

Exponential Calculation with Web Worker

{loading &&
Loading...
} {error &&
Error: {error}
} {!loading && !error && result !== null &&
Result: {result}
}
); };
登录后复制

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 < exponent; i++) {
    result *= base;
  }

  self.postMessage(result);
};

const App = () => {
  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 (
    

Exponential Calculation with Web Worker

{loading &&
Loading...
} {error &&
Error: {error}
} {!loading && !error && result !== null &&
Result: {result}
}
); }; 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!

以上是在 React Hooks 应用程序中利用 Web Worker 进行后台处理。的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!