Web Workers are a simple means to run JavaScript in background threads. The worker thread can perform tasks without interfering with the user interface.
To use Web Workers in Reactjs, you can follow below steps:
1. Create a Web Worker file:
```
// worker.js
self.addEventListener(‘message’, (event) => {
// Carry out a long running operation and send the result
postMessage(‘Long running operation is done’)
});
```
1. In your React component import the Web Worker file:
```
// App.js
import React, { useEffect, useState } from ‘react’;
const App = () => { const [messageFromWorker, setMessageFromWorker] = useState(‘’) let worker;
useEffect(() => { worker = new Worker(‘worker.js’); worker.addEventListener(‘message’, (event) => { setMessageFromWorker(event.data); }); worker.postMessage(‘Start the long running operation’); // cleanup return () => { worker.terminate(); }; }, []); return (It will instantiate a new worker using the `new Worker` function, pass it the path to the worker script file, and start the worker by calling `postMessage`. Event listener is used to listen to messages posted from the worker thread.
Note: When using with `create-react-app`, due to its default configuration, you can’t use a standalone worker script file within your React code directly, but need to use `worker-loader` module which allows your web worker code to be bundled along with your regular bundle.
Here is an example of using worker-loader:
1. Install worker-loader:
```
npm install worker-loader —save
```
1. Create a new worker file with .worker.js extension:
```
/* eslint-disable no-restricted-globals */
// worker.worker.js
self.addEventListener(‘message’, event /* { data } */) => {
// Post result back to the main thread
postMessage(/* result */);
});
```
1. In your react component import and use the worker.
```
// App.js
import Worker from ‘./worker.worker.js’;
const myWorker = new Worker();
myWorker.postMessage(‘Hello’);
myWorker.onmessage = (message) => console.log(message);
```
The worker-loader allows you to directly import your worker script file as class and the worker file gets automatically compiled and bundled with the rest of your application.