Before you go, check out these stories!

0
Hackernoon logoWeb Workers in React + Redux application by@shystruk

Web Workers in React + Redux application

Author profile picture

@shystrukVasyl Stokolosa

Photo by Ben Konfrst onย Unsplash

Run scripts in background threads and perform tasks without interfering with the user interface.

We all know that the JavaScript code executes in a single thread. It means that code will execute line by line and if a particular task takes a long time to complete everything else is held up until that task finishes. If we want to unload the main threat Web Workers what is all about.

โ˜๏ธ What you shouldย know

Web Workers is supported almost in all browsers. For slightly more controlled error handling and backwards compatibility, it is a better way to do a check.

if (window.Worker) {

...

}

Create only one instance, each call new Worker('worker.js') is going to load worker.js file. So, you may see something like that in Network.

React +ย Redux

With Redux update store is simple. So, we are going to have a place or a file where we create a Worker instance, export it and listen onmessage event where we dispatch an event when a data comes from the Worker.

In worker.js we may importScripts if we need to import some scripts to global worker scope. In Web Worker you may use XMLHttpRequest so in example below I import axios and use it for XHR calls. onmessage listener is called whenever new message bubbles through the worker. postMessage method sends a message to the workerโ€™s inner scope.

Use Worker instance. Import already existing Worker and call postMessage method with data which you want to pass to the Worker worker.js

Conclusion

Web Workers is powerful API you should definitely use it. It is good for background sync, prefetching data, ray tracing. Using web workers can have a significant impact on the performance of your web application.

๐Ÿ“ƒ Usefulย links

๐Ÿ‘ Thank you for reading. Suggestions, comments, thoughts are welcome ๐Ÿ‘

If you like this, clap, follow me on medium, twitter, github share with your friends ๐Ÿ˜Ž

Tags

Become a Hackolyte

Level up your reading game by joining Hacker Noon now!