How code splitting works - explained with example
Code splitting is a technique used to optimize web applications by breaking up the JavaScript bundle into smaller pieces (chunks) that can be loaded on demand. This improves the initial load time of the application by only loading the necessary code for the current page or feature, and deferring the loading of other code until it is needed.
How Code Splitting Works
Code splitting can be done using dynamic import()
statements or by configuring the bundler to split the code based on different entry points or routes.
Example of Code Splitting
Consider a simple React application with two pages: Home and About.
Step 1: Setup the Project
First, set up a basic React project:
-
Create a new React app:
npx create-react-app code-splitting-example cd code-splitting-example
-
Install React Router:
npm install react-router-dom
Step 2: Basic React Application
Create two components for the Home and About pages.
src/components/Home.js
:
import React from 'react';
const Home = () => {
return <h1>Home Page</h1>;
};
export default Home;
src/components/About.js
:
import React from 'react';
const About = () => {
return <h1>About Page</h1>;
};
export default About;
Step 3: Implement Code Splitting
Modify the main app to use React Router and implement code splitting with dynamic import()
statements.
src/App.js
:
import React, { Suspense, lazy } from 'react';
import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom';
const Home = lazy(() => import('./components/Home'));
const About = lazy(() => import('./components/About'));
function App() {
return (
<Router>
<div>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
</ul>
</nav>
<Suspense fallback={<div>Loading...</div>}>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
</Switch>
</Suspense>
</div>
</Router>
);
}
export default App;
Step 4: Build the Application
Run the build script to create the production build:
npm run build
What Happens During Code Splitting
In the App.js
file, we use React.lazy
to dynamically import the Home
and About
components. When the application is built, Webpack (which is used by Create React App) automatically splits the code into separate chunks. Each component is loaded only when the user navigates to the corresponding route.
Explanation
- React.lazy: This function is used to dynamically import a component. It returns a promise that resolves to the module containing the component.
- Suspense: This component is used to wrap the lazy-loaded components and provide a fallback UI (e.g., a loading spinner) while the component is being loaded.
- Dynamic Import: The
import()
function is used to split the code into separate chunks. The chunks are loaded on demand when the user navigates to the corresponding route.
Benefits of Code Splitting
- Improved Load Time: Only the necessary code for the current page is loaded initially, reducing the initial load time.
- Reduced Bundle Size: The JavaScript bundle is split into smaller chunks, making it more manageable and faster to download.
- Optimized Resource Loading: Unused code is not loaded until it is needed, improving the overall performance of the application.