React Code Splitting
React Code Splitting
React Code Splitting is the procedure of splitting the bundle files by which the files get easily loaded on the webpage.
The react application bundles the files by using tools such as Webpack or Browserfy. The Bundling process takes multiple files and merges them with a single file, called Bundle. The Bundle is used to load the entire app at once on the webpage. You can understand it by using the following example:
Suppose there is file App.js and Math.js, then the bundle merges both files into one.
App.js
import {sub} from './Math.js'; console.log(sub(26, 16)); // 10
Math.js
export function sub(a, b) { return a - b; }
The Bundle file is as follows:
function sub(a, b) { return a - b; } console.log(sub(26, 16)); // 10
As the application increases, the bundle also gets increases, mainly when we are using large third-party libraries. If the size of the bundle is getting large, then it will take a long time to load on the webpage.
To avoid the large bundling, we need to start the splitting of the bundle.
React version 16.6.0 released in the October 2018, and introduced the way to perform the splitting of code. The code-splitting feature is supported by Webpack and Browserify, which can create multiple bundles that can be loaded dynamically at runtime.
Code Splitting generally uses the React.lazy and Suspense tool/library, which helps you in the loading of a dependency lazily, and it only loads when the user requires it.
The code splitting improves the application performance, impact of the memory, and the downloaded Kilobytes (or Megabytes) size.
React.lazy
The best way of splitting the code into the app is by using the dynamic import() syntax. The React.lazy function allows us the rendering of a dynamic import as a regular component.
Example:
Before Using React.lazy()
import ExampleComponent from './ExampleComponent'; function MyComponent() { return (); }
After Using React.lazy()
const ExampleComponent = React.lazy(() => import('./ExampleComponent')); function MyComponent() { return (); }
Suspense
The Suspense component is used to handle the output when the lazy component is rendered and fetched.
const ExampleComponent = React.lazy(() => import('./ ExampleComponent')); function MyFunction() { return (}>Loading...
The fallback prop accepts the elements of React that you required to render while waiting for the component to load. We also can combine several lazy components with a single suspense component.
For Example:
const ExampleComponent = React.lazy(() => import('./ ExampleComponent')); const NewComponent = React.lazy(() => import('./ NewComponent')); function MyFunction() { return (}>Loading...