Categories
javascript lazy-loading react-router react-suspense reactjs

React Suspense lazy loading without fallback

I want to lazy load my components to decrease my initial bundle size and get components on the fly using code splitting using react router.

However, when using React Suspense, they force you to use a fallback for loading.

This wouldn’t work:

const lazyLoadComponent = Component =>
props => (
<Suspense> // Missing fallback property
<Component {...props} />
</Suspense>
);

In my case I am rendering html from the server so I don’t want to use a spinner.

This would create a useless flicker on my screen!
I.e.:

  • Html loads
  • Place holder appears
  • PageComponent for the route gets loaded
  • I have my own spinner that loads a feed from within the page component

In my case the html corresponds to the react component that gets loaded.

Is there any known hack to easily work around this problem (except for creating a loader for any route that copies the html (!!), which by the way, would make lazy loading useless).

I am a bit displeased with “forcing” us to add a loader and I don’t understand the logic behind the decision to make it mandatory.

I created an issue for this on Github: https://github.com/facebook/react/issues/19715

There isn’t a current clean solution using React-Router / React.

This is however foreseen in a future release using concurrent mode. As mentioned by Dan Abramov:

Regarding your concrete feature request, I think I can reframe it
slightly differently. It’s not that you want “optional fallback” since
that wouldn’t make sense for new screens (we’ve got to show
something). What I believe you’re looking for is a way to skip showing
the fallback if the content is already in HTML. This is precisely how
React behaves in Concurrent Mode so the feature request is already
implemented (and will eventually become the default behavior in a
stable release).

For me it is not a problem to wait, so currently I will omit lazy-loading the routes as this concerns a hobby-project and I have time to wait for a future release.