Is there a way to avoid blanks in react loadable components

358 Views Asked by At

I am using the react Loadable Components Package to lazily load components in my react app as shown in the snippet below:

import loadable from '@loadable/component'

const OtherComponent = loadable(() => import('./OtherComponent'))

function MyComponent() {
  return (
    <div>
      <OtherComponent />
    </div>
  )
}

The site is hosted on firebase hosting.

I noticed that sometimes the lazily imported component won't load until the page is refreshed manually.

On checking the logs I can see errors like

Chunk Failed to load

Once I refresh the page, the page gets loaded and the Chunk Failed to Load error is gone.

Is there a way to avoid this?

1

There are 1 best solutions below

0
On

You can have a retry(...) function. It wont make the problem completely disappear, but at least it will add some resilience upon failures:

export function retry(
  fn,
  {retries = 4, interval = 500, exponentialBackoff = true} = {}
) {
  return new Promise((resolve, reject) => {
    fn()
      .then(resolve)
      .catch(error => {
        setTimeout(() => {
          if (retries === 1) {
            reject(error)
            return
          }

          console.warn(`ChunkLoad failed. Will retry ${retries - 1} more times. Retrying...`)

          // Passing on "reject" is the important part
          retry(fn, {
            retries: retries - 1,
            interval: exponentialBackoff ? interval * 2 : interval
          }).then(resolve, reject)
        }, interval)
      })
  })
}

Than you can use it like this (with the default options):

loadable(() => retry(() => import(...)))