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?
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?
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.
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.