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).

Firebase is a pretty big module (more than the size of react, react-dom and next.js all combined), so we're importing only firebase/app and firebase/database that our app needs.

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

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