DEV Community

Guilherme Oenning
Guilherme Oenning

Posted on • Edited on • Originally published at goenning.net

How to retry when React lazy fails

React 16.6 has been released and it's now easier than ever to do code split within our React applications by using lazy and Suspense.

If you don't know what I'm talking about, you should definitely read this https://reactjs.org/blog/2018/10/23/react-v-16-6.html

After a few days monitoring a production application that is using lazy, I noticed some client-side errors like this:

Loading chunk 6 failed. (error: https://.../6.4e464a072cc0e5e27a07.js)
Loading CSS chunk 6 failed. (https://.../6.38a8cd5e9daba617fb66.css)    
Enter fullscreen mode Exit fullscreen mode

Why?!

I don't actually know why, but I can only assume this is related to the user network. Maybe they are on a slow 3G and there was a network hiccup? That's not a rare event, right?

Alright, if that's true, how do we solve that?

We can do the same thing that everyone does when a network request fails: retry it! 😄

How?

Did you know that the import(...) function that we use on lazy is just a function that returns a Promise? Which basically means that you can chain it just like any other Promise.

Below you can find a basic implementation of a retry function.

function retry(fn, retriesLeft = 5, interval = 1000) {
  return new Promise((resolve, reject) => {
    fn()
      .then(resolve)
      .catch((error) => {
        setTimeout(() => {
          if (retriesLeft === 1) {
            // reject('maximum retries exceeded');
            reject(error);
            return;
          }

          // Passing on "reject" is the important part
          retry(fn, retriesLeft - 1, interval).then(resolve, reject);
        }, interval);
      });
  });
}
Enter fullscreen mode Exit fullscreen mode

Source: https://gist.github.com/briancavalier/842626

Now we just need to apply it to our lazy import.

// Code split without retry login
const ProductList = lazy(() => import("./path/to/productlist"));

// Code split with retry login
const ProductList = lazy(() => retry(() => import("./path/to/productlist")));
Enter fullscreen mode Exit fullscreen mode

If the browser fails to download the module, it'll try again 5 times with a 1 second delay between each attempt. If even after 5 tries it import it, then an error is thrown.

That's all! 🎉

Thanks!

Top comments (21)

Collapse
 
maininfection profile image
Ricardo Machado

Hi Guilherme,

The reason for failing to download might be related to a recent deployment which changes the chunk hash and/or order number.

Also, don't forget to return the retry on the catch. Otherwise whoever gets the first retry cannot get the rejected error.

nice helper 👍

Collapse
 
debo07 profile image
Debajit Majumder

Could you please elaborate on this - "The reason for failing to download might be related to a recent deployment which changes the chunk hash and/or order number."?

I believe I am facing similar issue where just after a new deployment I able to see blank page with this console error.

Uncaught (in promise) Error: Loading chunk 7 failed.
(missing: domain.com/js/vendors~module1.bund...)
at HTMLScriptElement.i (bootstrap:120)

Collapse
 
0xdevalias profile image
Glenn 'devalias' Grant

I would suggest having a look at this blog and/or StackOverflow answer, as I feel they better describe the problem (and the 'why' of it), as well as providing some better solutions:

As Ricardo mentioned above in dev.to/maininfection/comment/727e this ChunkLoadError generally tends to happen when pushing new code, while the client's browser still has the old/outdated 'list of chunks' cached.

Collapse
 
goenning profile image
Guilherme Oenning

I don't think you need to do that. If the second retries fails, you get a new error, which is likely to be the same as the first retry error. But maybe I misunderstood your argument.

Collapse
 
maininfection profile image
Ricardo Machado

Ahhh I mislooked the last retry line. It actually passes the resolve and reject from the initial promise.

👍

Collapse
 
rainydaydy profile image
董雨

when use contenthash, if your file don't change, but add a new route, the chunkId will change,so the bundle is change but the filename doesn't change, when load chunk 1, the resource's chunkId maybe 2, so load chunk failed

Collapse
 
azrizhaziq profile image
Azriz Jasni • Edited

Nice helpers, there is a simple mistake on your code

  // from 
  retry(fn, interval, retriesLeft - 1).then(resolve, reject);

  // to
  retry(fn, retriesLeft - 1, interval).then(resolve, reject);

😆

Collapse
 
goenning profile image
Guilherme Oenning

Nice catch! Thank you 🙏

Collapse
 
lordlp profile image
LORD

Hi, maybe somebody could help me. I'm trying to use this example to avoid problems with chunk loading. But, in my case, it doesn't work. I have an error - Uncaught null. And I can't find a way how to resolve it. In this project, we are using react-router-config. And we are rendering routs like renderRoutes(this.props.routes).

Collapse
 
jacobmgevans profile image
Jacob Evans

My suggestion is to create a "repro" stackoverflow.com/help/minimal-rep...

It will help others help you 😁

Collapse
 
goenning profile image
Guilherme Oenning

Maybe not, but that'll depend a lot from one app to another. This is just one solution to the problem.

We actually mix both. We retry 5 times with a 500ms interval, if it still fails, then the ErrorBoundary catches the error and show a generic error page. I think that 2.5 sec is not that long if we can avoid having the user seeing an unnecessary error page.

Collapse
 
aditya_2911 profile image
M ADITYA • Edited

Thumbs up for this post. But I have a question as to when you are loading this new chunk...
for example: after a new deployment on the server, you definitely would fetch the updated chunk with the retries, but what about the initial bundle thats already been fetched (that stale bundle wouldn't be updated with the new bundle deployed right?). This could potentially lead to problems such as the newly fetched chunk being incompatible with the old bundle, etc.

Collapse
 
0xdevalias profile image
Glenn 'devalias' Grant

I would suggest having a look at this blog and/or StackOverflow answer, as I feel they better describe the problem (and the 'why' of it), as well as providing some better solutions:

As Ricardo mentioned above in dev.to/maininfection/comment/727e this ChunkLoadError generally tends to happen when pushing new code, while the client's browser still has the old/outdated 'list of chunks' cached.

Collapse
 
eschiebel profile image
Ed Schiebel • Edited

if the if (retriesLeft === 1) { block was moved above the setTimeout, the user wouldn't have to wait another interval for the final rejection.

Collapse
 
carpben profile image
Ben Carp

Checking your logs, can you say if this solution reduced the number of loading errors and by how much (in percentage)?

Collapse
 
psuranas profile image
Prateek Surana

Awesome helper function.

Can you please also tell me how can I use it with react-loadable, because the loader doesn't expect a promise actually, it expects the import function?

Collapse
 
kenshinman profile image
Kehinde Orilogbon

Honestly, this works for me. I have an app that is being used in a place with very slow network. This has helped me solve my client's problem. thanks @goenning

Collapse
 
pranavtheway profile image
Pranav Dave

Thank You so much for bringing this... but this solution perfectly fine in Chrome but it doesnt work in IE11, The retry doesnt happen at all... what could be the reason behind this behaviour!!??