Web Workers in React + Redux application

Written by shystruk | Published 2018/08/20
Tech Story Tags: javascript | react | web-development | programming | front-end-development

TLDRvia the TL;DR App

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 😎


Published by HackerNoon on 2018/08/20