Why Is Lazy Loading Not The Default For React?

- 1 answer

I am just working through a React course and the current topic is lazy loading.

I was wondering why lazy loading is not the default and taken care of by React without forcing the developer to write repetitive code?


In the course, we want to load the Posts component lazily, because in this component we only render it when on a certain route. Therefore he replaces

import Posts from './containers/posts'


const Posts = React.lazy(() => import('./containers/posts'))

and where it is used he replaces

<Route path='/posts' component={Posts}>


  render={() => (

so basically just wrapping the component we want to lazyload in a certain React component.



React is not handling the lazy loading by itself but relies on the functionality of the underlying bundler (Webpack). In particular, the bundler converts the import() statements (which is the proposal for the dynamic import) to something which could be processed by the majority of the browsers. Thus, to enforce the underlying building process to load a specific module lazy you also have to use import().

In general, splitting into multiple chunks (that's what is happening on build when lazy loading is used) might be good (e.g. for mobile users, as mentioned by @Prashant Adhikari) but also leads to additional delays while using the page because the files have to be transferred over the network one by one first. Thus, it's also not an option to have lazy loading everywhere. In fact, this issue might disappear in the future (esp. with some "intelligent" preload mechanism in HTTP/2) but for the majority of applications the best practice over the last years seems to be generating a fat JS file for application-related scripts plus a vendor.js for the dependencies.

However, introduction of lazy loading might be reasonable in order to minimize the page loading time. Esp. for bigger applications (like Stack Overflow) it makes sense to preload the modules require to depict the primary content (e.g. Questions) and lazy load the less frequent pages (e.g. User settings).