ReactJS :: Code splitting

As with any single page application, everything gets bundled into one file that can quickly bloom in size if it does not get kept in check. Tools such as Webpack can help split this bundle up into more manageable chunks that can then be requested as needed.

As React encourages creating lots of smaller components, there are plenty of opportunities to break up the bundle. The react-loadable package enables a component to define exactly what it needs to render and Webpack can automatically split up its bundle to accommodate this.

const LoadableButton = Loadable({
  loader: () => import(‘./Button’),
  loading: () => <div>Loading...</div>,

Loadable is a HOC that will dynamically import anything the component needs. It takes a few settings, such as what to show while everything loads in, which makes it highly customisable. LoadableButton can then be used as a regular component without issue.

For larger applications with routing, it may be more beneficial to split by route instead of component. Common paths can be pulled in with one request, and can help speed things up. It is important to have a balance between the number of bundles and their overall size, which will change depending on the needs of the application.

More details about react-loadable can be found here.

Leave a Reply

Your email address will not be published. Required fields are marked *