Lazy Loading Components

We use a lot of React components in our applications. We include them in our main JavaScript bundle or in one of the page's JavaScript bundles. Sometimes some of these components are pretty big.

For example, this is a pretty simple blog site we built with Next.js based on markdown.

It also supports syntax highlighting. For that, we use react-highlight, and it's a pretty big module.

Actually, the react-highlight module itself is very small but it's the highlight.js module used inside that is bulky.

Here's how we use it:

import Highlight from 'react-highlight';

// some other code
  <Highlight innerHTML>{marked(blogPostMarkdown)}</Highlight>

// some other code

Since it's used in almost all pages, react-highlight is included in our main JavaScript bundle.

But we don't need to use the syntax highlighter on every page. It's only needed when there's a code sample in the blog post.

So, if we can load react-highlight only when needed, that will reduce the initial bundle dramatically, and that will help our app load faster.

This is something we can do with Next.js. Let's get started.