DEV Community

Cover image for Code splitting (bundle-split) in React
Nitsan Cohen
Nitsan Cohen

Posted on • Updated on

Code splitting (bundle-split) in React

As you probably already know, when you build your React app (npm run build), Webpack will bundle all of your files into one big chunk.

If your app is not that big that's usually just fine. But what happens when your app grows dramatically? You can end up with a really big JS file and that can hurt your UX, especially the initial loading time.

Luckily there is a simple solution we can implement. Its name is code-splitting. By splitting our bundle, we can tell React (or Webpack) to load only the code that is absolutely necessary for the initial load (-for the current page, for example).

Later, we can "lazy load" the rest of our code upon request (when navigating or scrolling down).

One of the easiest ways to implement code splitting is by using a dynamic import. As the name suggests, the dynamic import will asynchronously import our file and will return a promise.

It looks like this:

export default (numA, numB) => numA * numB

async function loadModule() {

 const dynamicImport = await import('./file1')

 dynamicImport.default(10, 10)

loadModule() //output: 100
Enter fullscreen mode Exit fullscreen mode

But what if we want to dynamically import a component?
Let's assume we have a component that is used by our app only on page B. We don't want to import it when we are on page A. Well, with React.lazy it's a breeze!

Have a look at the attached image. All we have to do is use React.lazy to import our component. This component will now be excluded from our bundle and imported only on runtime when we load that specific page.
We are also using the Suspense component to render a fallback while the user is retrieving the bundle.

Image description

  • For more posts like this follow me on LinkedIn

  • I work as frontend & content developer for Bit - a toolchain for component-driven development (Forget monolithic apps and distribute to component-driven software).

Top comments (0)