Lazy Loading Modules

Next.js does automatic code splitting and it is based on the pages in your app. For example, if one of your modules is used at-least in half of your pages, then it moves into the main JavaScript bundle. If not, that module stays inside the page's bundle.

This is a pretty decent default setup. But sometimes, we need much better control for loading modules. For example, have a look at the following scenario, where:

  • We are building a hacker news clone based on the official firebase API,
  • We fetch the data on the server to do SSR,
  • We also fetch data in the client side when needed (when switching pages).

In this case, our main app bundle contains the firebase module, simply because it is used in all of our pages. It is a pretty big module. (More than the size of react, react-dom and next.js all combined)

But when it comes to client side, we only need it when the user starts navigating into a different page. So, if we can load the firebase module at that time, we can improve the initial loading of our app.

That is exactly what we are trying to do with this lesson.