Non blocking updates in React
Sometimes, a few updates/computations take up a lot of time. They block the UI from updating, which makes it look as if things are slow. I am not talking about asynchronous data fetches which take time.
TL DR; We will be using web workers as a solution along with Hooks.
Consider this for example
When we enter the input here, it takes time to update. And it waits for the update to show up until, till the result calculation is not finished. Fibonacci for large numbers is expensive. It even freezes your browser tab if the input is long.
This is the worker, which has to be statically served. (Put in
We communicate with the worker using events. Look at the code here, we are listening 👂 to
message events. We process the data according to
type passed and return the result as a message.
If you can guess right, we will have to listen to these messages from the worker in our component. Our component goes like this.
If you are using Webpack, you can load it into your component with
worker-loader!thread.js. We are directly using
Worker() to load it from the
Here is the codesandbox demo - https://codesandbox.io/s/funny-nightingale-5kxo1
Here is the Effect Hook documentation for reference.
We are adding the listeners for the messages in the first effect, where the dependencies are
, which means this will run when the component is mounting and unmounting.
And in the second effect, we send a message to the worker whenever the value changes.
We can see a huge performance bump with workers when we compare it to the first demo. The load is taken up by the browser now.
That's how you can use web workers in React. Thanks for reading!
Keep on Hacking! ✌
By Aravind Balla who is a friendly human, building things for himself, and sometimes for others. You should hit him up on Twitter!