Code Splitting in React apps with Suspense

The easy way to keep your applications’ bundle size small.

Matthew Brown
JavaScript in Plain English
3 min readOct 6, 2020

--

Photo by Oscar Nord on Unsplash

In this article, I am going to give a demo of how to use React’s Suspense to show you how simple it is to implement code-splitting and help to keep your overall bundle size as small as possible.

Why code-splitting?

If you using webpack to build your React application which Creates React App does by default then it is bundling your code together during the build.

You will need to pay attention to the size of this bundle as your application grows especially so with the external libraries you are adding. Otherwise, as your bundle size grows your application can start taking a long time for the initial load.

This is where code-splitting really comes in handy. Once implemented webpack will automatically split out your code into smaller bundles.

It can be difficult to know exactly where to start splitting your code up, but there are logical ways to do it. One good approach is split for each route in the app. So you would split up the bundle by each route declared in your app router.

Let’s build an example application

Now that we know why code-splitting is good for development let’s jump right in and build an example. We will be going through step by step and feel free to check out the full finished example code in Github.

We will need to create a new application using Create React App and install React Router to handle the routing in our demo application.

npx create-react-app react-suspense-demo
cd react-suspense-demo
npm install react-router-dom

The next step is we will create a handful of components for our routes. These will all look pretty much the same. Just placeholders for each route we are creating for the app in the next step.

--

--

I am a senior software engineer. My passions include software development, anything technology related, and cars.