How to use Web Worker in React?

sharath .v
2 min readOct 25, 2023

Using web workers in a React application is quite similar to using them in a regular JavaScript application. You can create a separate worker file and communicate with it from your React components. Here’s a basic example:

1. Create a Web Worker file (e.g., worker.js):

// worker.js
onmessage = function (event) {
console.log('Received message from the main thread:', event.data);

// Perform some computation
const result = event.data * 2;

// Send the result back to the main thread
postMessage(result);
};

2. Set up a Web Worker in a React Component:

// MyComponent.js
import React, { useState, useEffect } from 'react';

const MyComponent = () => {
const [result, setResult] = useState(null);
const [worker, setWorker] = useState(null);

useEffect(() => {
// Create a new web worker
const myWorker = new Worker('worker.js');

// Set up event listener for messages from the worker
myWorker.onmessage = function (event) {
console.log('Received result from worker:', event.data);
setResult(event.data);
};

// Save the worker instance to state
setWorker(myWorker);

// Clean up the worker when the component unmounts
return () => {
myWorker.terminate();
};
}, []); // Run this effect only once when the component mounts

const handleClick = () => {
// Send a message to the worker
if (worker) {
worker.postMessage(5); // Send the number 5 to the worker
}
};

return (
<div>
<p>Result from the worker: {result}</p>
<button onClick={handleClick}>Calculate in Web Worker</button>
</div>
);
};

export default MyComponent;

3. Using the Component in your App:

// App.js
import React from 'react';
import MyComponent from './MyComponent';

const App = () => {
return (
<div>
<h1>React App with Web Worker</h1>
<MyComponent />
</div>
);
};

export default App;

In this example, the MyComponent sets up a web worker when it mounts. When the button is clicked, it sends a message to the web worker, which performs some computation and sends the result back to the main thread. The result is then displayed in the React component.

Remember to handle the termination of the web worker when the component is unmounted to avoid memory leaks. This example demonstrates a basic use case, and you can extend it based on your specific requirements.

--

--