DEV Community

Martins Olumide
Martins Olumide

Posted on • Edited on

How to use Web Worker in React with TypeScript

Table of Contents

  • What are web workers

  • Prerequisites

  • Initializing a project (VITE)

  • Connecting the dots

  • Wrapping up

What are web workers

According to MDN, Web Workers are a simple means for web content to run scripts in background threads. The worker thread can perform tasks without interfering with the user interface. In addition, they can make network requests using the fetch() or XMLHttpRequest APIs. Once created, a worker can send messages to the JavaScript code that created it by posting messages to an event handler specified by that code (and vice versa).

JavaScript as we all know is single-threaded I.E it can only execute only one thing at a time, it simple cannot multi-task like other languages out there. So, the Idea behind web worker is to aid or acts as an auxillary thread executer, taking the load off the Main thread. In some situations, we might want to fetch some resources that takes time to respond or perform some CPU intensive task that may cause the UI to hang or freeze, that's where Web Workers comes in. We take such Task or Computations and execute them in Background thread away from the main thread.

Prerequisites

Make sure you have a React project created, either CRA or VITE anyone. If you can't create one, follow this step. I'll be using VITE.

Initializing a project (VITE)

//Make sure you have NODE installed
//In your terminal, type this

npm create vite@latest

/**This will bring a prompt telling you to name your project folder, after typing a name, press

Enter, then you'll be asked what framework (Choose React obviously), and choose TypeScript if

you want. After that, your project is all set and we can begin writing code.**/
Enter fullscreen mode Exit fullscreen mode

Connecting the dots

So now, after installations you should create a Worker folder (not a must but more conventional way of doing it). So we have

//src/Worker/worker.ts
const workerFunction = function () {
//we perform every operation we want in this function right here
   self.onmessage = (event: MessageEvent) => {
      console.log(event.data);

      postMessage('Message has been gotten!');
   };
};

//This stringifies the whole function
let codeToString = workerFunction.toString();
//This brings out the code in the bracket in string
let mainCode = codeToString.substring(codeToString.indexOf('{') + 1, codeToString.LastIndexOf('}'));
//convert the code into a raw data
let blob = new Blob([mainCode], { type: 'application/javascript' });
//A url is made out of the blob object and we're good to go
let worker_script = URL.createObjectURL(blob);

export default worker_script;
Enter fullscreen mode Exit fullscreen mode

Here is my React Component accessing the worker file.

//src/App.tsx
import { useEffect } from 'react';
import worker_script from './Worker/worker';

let worker: Worker;

function App() {
   if(window.Worker)
     worker = new Worker(worker_script);

   useEffect(() => {
      worker.postMessage('Beunos Dias!');
   });
   return <p>Web Workers</p>;
}
export default App;

Enter fullscreen mode Exit fullscreen mode

Because my useEffect doesn't have a dependency, the worker.postMessage function will be called once the page load and no more, until you refresh the page again.

Wrapping Up

once that is done, you can just run your code with a simple npm run dev this will build your whole project and serve it on port 5173, yours might be a different port due to different configuration. In addtion, the build up process is lightning fast ⚡⚡, I recommend using VITE for your projects...

Top comments (2)

Collapse
 
ilkhomkurbanov profile image
Ilkhom Kurbanov • Edited

cleanest code ever! thank you!!! I spent entire day playing with various comlink plugins for vite.... man, who knew it could be that simple.... the only think, I would probably terminate worker on unmount.

Collapse
 
edimedia-mutoke profile image
Edimedia Mutoke

Amazing !

What if the webworker has npm dependecies ?