ReactJS Code Splitting in 3 minutes

So, do you want to reduce the first load time in your ReactJS project? if you said yes, then just follow this technique in order to accomplish that.


By default, all your code gets bundled in fewer files, and that’s a good technique to avoid making many HTTP requests, however this is not healthy when you have a big app and probably your customers won’t interact with all sections/pages of your web, that’s why you need some sort of Code Splitting feature that makes your project load chunks of logic as required. The goodness of that is pretty clear.

What to do?

Let’s say you have this basic App.js file:

Basic initial ReactJS App.js file

And let’s say that the <Content /> component is so packed with so much logic and therefore it will slow down your page load.

Well, we might want to load it asynchronously somehow; using the Code Splitting technique you can aim that easily like this:

<Content /> component loaded asynchronously

Now, as you can see, I just replaced the traditional import sentence with this:

const Content = React.lazy(() => import(“./Content”));

Also I placed the <Content /> component inside a <Suspense /> component which I imported from react. Finally the <Suspense /> component requires a fallback prop with a JSX content to render meanwhile the component is loading, that’s why you’ll see a loading… text for a few seconds and then the real content.

So, if you need to display some content to the user while the page is loading, this is nice and clean way to do it.

That’s all

I hope this mini tutorial can help you to understand the Code Splitting technique with a simple example, if you want to read more details about this, please go to the official docs which I think is pretty clear.