Home > Blockchain >  setState is too laggy in React
setState is too laggy in React

Time:10-13

I use pdf-lib(JS library) in my React project. I am doing heavy work with the library with async/await and would like to update progress bar by updating state. Even though I call setState in setTimeout, the state is updated after the heavy work ends. So the progress bar shows only 0% and 100%. Could you kindly figure it out? I can't share my code, but if you want, I will show a little.

CodePudding user response:

Remember that "asynchronous" is does not mean it runs "in parallel". It just means that code gets to run "out of order" in a controlled fashion.

Your page thread is just a single thread, so if you have a long-running function, you can mark that function as async or run it with setTimeout as much as you like but while your function code runs, nothing else gets to run (although in the case of async: only until the code hits an await, which I'm assuming pdf-kit does not use).

If you need to do heavy lifting, use a service worker, which is a special API for exactly this thing, running heavy workloads in a separate thread so that you don't block the main page thread.

  • Related