Code splitting is a technique to split the JavaScript bundle into smaller chunks
, which are loaded on-demand
.
-
Use React.lazy() to lazily import components.
-
Wrap components with Suspense to handle loading.
-
Configure your build tool (e.g., Webpack) for dynamic imports.
const CodeSplit = () => { return <div>My component!</div>; }; export default CodeSplit;
import React, { lazy, Suspense } from "react"; const CodeSplit = lazy(() => import("./Others/CodeSplit")); function App() { return ( <div> <Suspense fallback={<div>Loading...</div>}> <CodeSplit /> </Suspense> </div> ); }
// npm install webpack webpack-cli --save-dev const path = require('path'); module.exports = { // other webpack configuration... output: { filename: '[name].bundle.js', path: path.resolve(__dirname, 'dist'), }, };
-
React.lazy is a function that allows you to
load a component lazily
. -
It enables code splitting by allowing you to import a component asynchronously/dynamically, meaning the component is loaded only when needed.
-
The Suspense component is used to display a fallback UI while the lazily loaded component is being fetched.
import React, { lazy, Suspense } from "react";
const CodeSplit = lazy(() => import("./Others/CodeSplit"));
function App() {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<CodeSplit />
</Suspense>
</div>
);
}
Pros of Code Splitting | Description |
---|---|
Faster Initial Load Time | Code splitting reduces the initial load time of your application by only loading the necessary code for the current view or feature. Good for performance. |
Optimized Bandwidth Usage | By loading only the code needed for a specific page, it reduces the amount of data transferred over the network. Good for slow networks. |
Improved Caching | Smaller, more focused code chunks are more likely to be cached by the browser. |
Parallel Loading | Multiple smaller chunks can be loaded simultaneously, leading to faster overall loading times. |
Easier Maintenance | Code splitting can make your codebase more modular, independent, and easier to maintain. |
Cons of Code Splitting | Description |
---|---|
Complexity | Implementing code splitting introduces additional complexity to your application. This complexity can make the development process slow. |
Tooling Dependencies | Proper code splitting often requires specific build tools and configurations, such as Webpack and Babel. Managing these tools is challenging. |
Potential for Runtime Errors | Dynamically loading code at runtime can introduce the possibility of runtime errors. Careful testing is necessary to catch such issues. |
Increased Number of Requests | Code splitting may increase the number of HTTP requests needed to fetch all the necessary chunks. This can impact performance. |
Learning Curve | Developers who are new to code splitting may need time to understand the concepts and best practices. This can be a challenging. |
The import() function returns a promise that allow dyanmic loading of modules
.
import React, { lazy, Suspense } from "react";
const CodeSplit = lazy(() => import("./Others/CodeSplit"));
function App() {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<CodeSplit />
</Suspense>
</div>
);
}
The fallback prop provides a loading indicator
or UI while the dynamically imported component is being loaded.
Yes
, using dynamic import() for CSS files allows you to load styles on-demand along with the corresponding components.
Use tools like Webpack Bundle Analyzer
to analyze the size and composition of chunks.