I recently found myself in a situation where I needed to perform a processor-intensive search functionality on the client-side. I was implementing fusejs to fuzzy search through a large volume of data, on a React/Redux app, but I didn’t want the app to freeze while the search was going on.
The solution to keep my app from freezing? Use a web worker. But I also wanted that solution to be scalable. That means it needed to have the ability to create multiple web workers to process various large tasks — tasks my app may need to do in the future. Yet when I went to find an npm package for Redux that supported multiple web workers, I couldn’t find one. So I built redux-middleware-workers.
You may be wondering, what is a redux middleware worker? And why would I need that npm package? Well, here are some answers to those questions.
What is a web worker?
A web worker is JavaScript that runs in a separate thread (per worker) than the single threaded event loop in the browser. A worker can perform a lot of different tasks. It can make api calls, perform large tasks (i.e. searching through a large volume of data), or many other performance-heavy operations. The most commonly used methods for a web worker are:
addEventListener: this method is called with a string (usually ‘message’) and function to be called.
postMessage: Whatever data is passed to this method is passed to the worker. Note that you cannot pass a web worker methods.
onmessage: This method is typically what triggers the eventListener, and it is here that web worker will perform tasks. On completion, another postMessage is called that triggers the addEventListener.
Why would you use a web worker?
The main reason to use a web worker is to improve performance. If your client-side application is processing large tasks, an intensive activity (like a fuzzy search) can be blocking, having the effect of making the UI freeze. That’s a terrible user experience. This can happen even with the latest and fastest JavaScript engines.
Web workers are non-blocking. This means that while the browser is running your application on a single threaded event loop — which means one event handled at a time instead of in parallel — web workers allow for events to processed in multiple threads or multiple events in parallel.
Redux-middleware-workers
In order for web workers in your application to respond to actions and follow the redux pattern, the web workers will have to be initialized and managed in a redux middleware. The npm package I released, redux-middleware-workers, allows you to add multiple web workers to your project. The workers are initialized with the redux store, and they perform their tasks when the appropriate redux action is dispatched. When the worker is done, it will also fire an action.
If you want to learn more and see the package in action, here is a working example in a simple react/redux project.