DEV Community

Cover image for Code Splitting in React
Humza Hasan
Humza Hasan

Posted on

Code Splitting in React

If you are someone like me who has just finished few projects in React and got his/her hand dirty with hooks, state management, etc. Your next stop should be performance.

WHY ?

I don't know about you but a slow website me make sometimes wanna do this 👇

Slow computer

So without further adieu, lets get started!

So before jumping into "What is Code Splitting in React?", let's first understand why do we need this at all.

Traditionally in React, all components code are bundled into one single bundle.js file with the help of bundler such as Webpack, Rollup, etc. This helps the application to download the entire app code at once and eliminate the need of making further subsequent HTTP request. But the drawback here is as and when the application grows, so does the size of the bundle file which leads to a longer initial load time. To solve this problem Code Splitting was introduced in React.

Code Splitting is a feature where we can create multiple bundles that can be dynamically loaded on runtime. This helps us to lazy load just the things that are currently needed by the user, which can dramatically improve the performance of your app.

Few common methods of Code Splitting in React are as follows:

  • Dynamic Export
  • Lazy Loading
  • Route-based code splitting
  • Named Export

With the help of these techniques we don't reduce the number of lines of code in our app but we avoid loading code that the user may never need, and reduced the amount of code needed during the initial load, thus helping us improve the overall performance of the app.

Splitting

You can also check out these amazing resources for in-depth understanding:

Discussion (0)