A Guide to Code Splitting and Dynamic Imports
Code Splitting
Definition: Code splitting is a strategy or technique to break down large JavaScript bundles into smaller chunks. These chunks can then be loaded on demand, which can significantly improve the performance of web applications.
Purpose:
How It Works:
Code splitting using React.Lazy and suspense
import React, { Suspense } from 'react';
// Dynamically import the component
const OtherComponent = React.lazy(() => import('./OtherComponent'));
function MyComponent() {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<OtherComponent />
</Suspense>
</div>
);
}
export default MyComponent;
Dynamic Imports
Definition: Dynamic imports are a feature of JavaScript that allows the importation of modules at runtime, rather than at the start of the script. This is done using the import() function, which returns a promise that resolves to the module.
Purpose:
How It Works:
Relationship Between Code Splitting and Dynamic Imports
Here are some common scenarios where dynamic imports are used, along with examples:
Recommended by LinkedIn
1. Lazy Loading Components
Lazy loading components is a common use case for dynamic imports in React. This is typically done with React.lazy and Suspense.
Example:
import React, { Suspense, lazy } from 'react';
// Dynamically import the component
const HomePage = lazy(() => import('./HomePage'));
const AboutPage = lazy(() => import('./AboutPage'));
function App() {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<HomePage />
<AboutPage />
</Suspense>
</div>
);
}
export default App;
2. Route-Based Code Splitting
In single-page applications (SPAs), it's common to split code based on routes so that each route loads its respective code only when the route is visited.
Example:
import React, { Suspense, lazy } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
// Dynamically import the components for routes
const HomePage = lazy(() => import('./HomePage'));
const AboutPage = lazy(() => import('./AboutPage'));
function App() {
return (
<Router>
<Suspense fallback={<div>Loading...</div>}>
<Switch>
<Route path="/home" component={HomePage} />
<Route path="/about" component={AboutPage} />
</Switch>
</Suspense>
</Router>
);
}
export default App;
3. Conditional Component Loading
Load components conditionally based on user interactions, such as button clicks.
Example:
import React, { useState, Suspense, lazy } from 'react';
function App() {
const [showAbout, setShowAbout] = useState(false);
// Dynamically import the AboutPage component
const AboutPage = lazy(() => import('./AboutPage'));
return (
<div>
<button onClick={() => setShowAbout(true)}>Show About Page</button>
<Suspense fallback={<div>Loading...</div>}>
{showAbout && <AboutPage />}
</Suspense>
</div>
);
}
export default App;
4. Loading Large Libraries or Utilities
Sometimes, you might want to load large libraries or utilities only when they are needed to save on initial bundle size.
Example:
import React, { useState } from 'react';
function App() {
const [chartData, setChartData] = useState(null);
const loadChartLibrary = async () => {
const { Chart } = await import('chart.js');
// Initialize chart with data
setChartData(new Chart(/* ... */));
};
return (
<div>
<button onClick={loadChartLibrary}>Load Chart</button>
{chartData && <div>{/* Render chart here */}</div>}
</div>
);
}
export default App;
<button onClick={() =>
import("../sum.js").then
alert(module.sum (2,2
})
}}>Add 2 + 2</button>