Sitemap

Webpack + React Optimised Fix ChunkLoadError

3 min readMar 9, 2021

--

If you have used lazy loading with react and it is very likely possible you will encounter with chunk loading issue, it generally causes by network hiccups and can interrupt the user experience.

Check the previous article In this series.
Webpack + React Optimised from scratch
Webpack + React Optimised Differential Serving

This issue is something you can not reproduce very easily but it will come intermittently.

Can we fix this issue?

Yes, we can fix this.

To fix this issue we will try to re-download the module and will repeat this process for some time if we get the same issue over again for some interval.

Let fix this step by step::

  1. We will import our component with react-lazy.
const Component = React.lazy(()=> import('./to/component'));

You already have done that and got the same issues. To fix that we need to change something here. Let's move ahead.

2. Create a function that will re-download our failed module

const retry = (fn, retriesLeft = 5, interval=1000) => {...}

In the above, we have written a function that will retry downloading failed module.

In above function you can see three parameters

fn: This is our import callback function ()=> import(‘./to/component’) same as mentioned in 1. point.

retriesLeft: It tells the number of calls we can try to redownload our module.

interval: After how much time we want to re-trigger our call to re-download the package.

Get Shailesh Jha’s stories in your inbox

Join Medium for free to get updates from this writer.

3. Now we will see the internal working.

const 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); }); });
}
Press enter or click to view image in full size

4. Let’s create our final lazyLoad function

const lazyLoad = (fn) => React.lazy(() => retry(fn, 4, 1500));// or defaultconst lazyLoad = (fn) => React.lazy(() => retry(fn));export default lazyLoad;

We will export this lazyLoad and we can utilize this in place of React.lazy we have used to import in our component.

5. Now we will use this function in our project

const Component = lazyLoad(()=> import('./to/component'));

Conclusion

We have created a function that will try to re-download our failed module at a given interval for the number of retries we want. In this way, we can serve a better user experience without worrying about network hiccups and use the chunking advantages.

Thanks, Happy reading ❤️

--

--

Shailesh Jha
Shailesh Jha

Written by Shailesh Jha

Consultant | Full Stack Developer