Blog

Code Splitting

published 2021-08-07

What is Code Splitting?

As the stuff we build gets bigger, uses more libraries and other assets, the bundle for our apps get pretty big. The bigger our app is the longer our loading times, which leads to a worse user experience and a less accessible app.

Code splitting helps solve this problem. Code splitting "splits" your bundle, loading parts of your app only when they are needed. This means that your app initially loads faster, and the parts that the user don't use aren't even loaded. This "load as needed" process is called lazy loading.

How Do I Do It?

Your bundler (e.g. Webpack, Rollup) handles bundling. It makes sense then that your bundler handles code splitting.

In React, one way of implementing code splitting is with dynamic imports. For example:

import(x).then(x => x.doY);

Webpack sees this and will automatically implement code splitting for you. For other bundlers it might look a little different, so if you're using something else it would probably be a good idea to check the docs for your specific bundler.

There is also a React.lazy package that can implement it, however it isn't fully implemented. A good alternative (according to the React docs) is the loadable components library.

Implementing code splitting well means only loading what is needed for whatever section of the page they are on, but not needing to load things super frequently (which might lead to the user noticing not everything is loaded, which is bad for user experience).

Conclusion

So that is what code splitting is and how it works. It's not super hard to implement, but it has a huge impact. For more info, the React docs has a good page on this.