{"id":7583,"date":"2025-07-05T15:32:24","date_gmt":"2025-07-05T15:32:23","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=7583"},"modified":"2025-07-05T15:32:24","modified_gmt":"2025-07-05T15:32:23","slug":"code-splitting-in-react-with-lazy-suspense-4","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/code-splitting-in-react-with-lazy-suspense-4\/","title":{"rendered":"Code Splitting in React with Lazy &amp; Suspense"},"content":{"rendered":"<h1>Code Splitting in React with Lazy &amp; Suspense<\/h1>\n<p>React has gained immense popularity due to its component-based architecture, which allows developers to build efficient and scalable user interfaces. One technique that further enhances performance in React applications is <strong>code splitting<\/strong>. This post delves into <strong>code splitting<\/strong> using <strong>React.lazy<\/strong> and <strong>React.Suspense<\/strong>, two powerful features introduced in React 16.6.<\/p>\n<h2>What is Code Splitting?<\/h2>\n<p>Code splitting is a technique that allows you to split your application\u2019s bundle into smaller chunks. Instead of loading the entire application on the first load, you can load only the components that are required for the initial render. This approach reduces the load time and enhances the overall performance of your application.<\/p>\n<p>In React, code splitting is facilitated through dynamic imports and can easily be achieved using <strong>React.lazy()<\/strong> and <strong>React.Suspense<\/strong>.<\/p>\n<h2>Understanding React.lazy<\/h2>\n<p><strong>React.lazy()<\/strong> is a built-in function that allows you to render a dynamic import as a regular component. By using this function, React can automatically split your application into smaller bundles and load components as needed.<\/p>\n<h3>How to Use React.lazy<\/h3>\n<p>The syntax for using <strong>React.lazy<\/strong> is straightforward:<\/p>\n<pre><code>const LazyComponent = React.lazy(() =&gt; import('.\/LazyComponent'));<\/code><\/pre>\n<p>In this example, we are importing a component called <strong>LazyComponent<\/strong> using a dynamic import. This means that the code for <strong>LazyComponent<\/strong> will be loaded only when required, which improves the initial loading time.<\/p>\n<h3>Example of Code Splitting with React.lazy<\/h3>\n<p>Let\u2019s say we have a simple React application that has two components: a main component and a secondary component.<\/p>\n<pre><code>function MainComponent() {\n    return (\n        &lt;div&gt;\n            &lt;h1&gt;Welcome to the Main Component&lt;\/h1&gt;\n            &lt;LazyComponent \/&gt;\n        &lt;\/div&gt;\n    );\n}\n\nconst LazyComponent = React.lazy(() =&gt; import('.\/LazyComponent'));\n<\/code><\/pre>\n<p>In the above example, <strong>LazyComponent<\/strong> will be loaded when the <strong>MainComponent<\/strong> is rendered.<\/p>\n<h2>Introducing React.Suspense<\/h2>\n<p>Along with <strong>React.lazy<\/strong>, React provides <strong>React.Suspense<\/strong> to handle loading states while the lazy-loaded component is being fetched. <strong>React.Suspense<\/strong> allows you to define a fallback UI that will be displayed until the lazy component is loaded successfully.<\/p>\n<h3>Using React.Suspense<\/h3>\n<p>Here is how you can use <strong>React.Suspense<\/strong> in your application:<\/p>\n<pre><code>import React, { Suspense } from 'react';\n\nconst LazyComponent = React.lazy(() =&gt; import('.\/LazyComponent'));\n\nfunction App() {\n    return (\n        &lt;Suspense fallback=&quot;Loading...&quot;&gt;\n            &lt;MainComponent \/&gt;\n        &lt;\/Suspense&gt;\n    );\n}\n<\/code><\/pre>\n<p>In the above code, we wrap the <strong>MainComponent<\/strong> with <strong>Suspense<\/strong> and provide a fallback prop that displays a loading message (&#8220;Loading&#8230;&#8221;) while the <strong>LazyComponent<\/strong> is being loaded.<\/p>\n<h2>Combining Code Splitting with React Router<\/h2>\n<p>Code splitting can also be integrated with <strong>React Router<\/strong> for more effective chunk loading. React Router allows you to define routes, and you can use <strong>React.lazy<\/strong> to load route components dynamically.<\/p>\n<h3>Example with React Router<\/h3>\n<pre><code>import React, { Suspense } from 'react';\nimport { BrowserRouter as Router, Route, Switch } from 'react-router-dom';\n\nconst HomeComponent = React.lazy(() =&gt; import('.\/HomeComponent'));\nconst AboutComponent = React.lazy(() =&gt; import('.\/AboutComponent'));\n\nfunction App() {\n    return (\n        &lt;Router&gt;\n            &lt;Suspense fallback=&quot;Loading...&quot;&gt;\n                &lt;Switch&gt;\n                    &lt;Route path=&quot;\/&quot; exact component={HomeComponent} \/&gt;\n                    &lt;Route path=&quot;\/about&quot; component={AboutComponent} \/&gt;\n                &lt;\/Switch&gt;\n            &lt;\/Suspense&gt;\n        &lt;\/Router&gt;\n    );\n}\n<\/code><\/pre>\n<p>In this example, the <strong>HomeComponent<\/strong> and <strong>AboutComponent<\/strong> will be loaded dynamically when the corresponding routes are accessed, improving the load time of your application.<\/p>\n<h2>Benefits of Code Splitting<\/h2>\n<p>The benefits of implementing code splitting in your React application are manifold:<\/p>\n<ul>\n<li><strong>Improved Load Time:<\/strong> Loading only the components required reduces initial load time.<\/li>\n<li><strong>Better User Experience:<\/strong> Users can start interacting with the application while the remaining components load in the background.<\/li>\n<li><strong>Optimized Bundle Size:<\/strong> Smaller bundles help in reducing the overall size of the application, thus improving performance.<\/li>\n<\/ul>\n<h2>Considerations and Best Practices<\/h2>\n<p>While code splitting can significantly enhance performance, there are a few considerations to keep in mind:<\/p>\n<ul>\n<li><strong>Testing:<\/strong> Ensure that the lazy-loaded components perform correctly and that the loading states don&#8217;t lead to a poor user experience.<\/li>\n<li><strong>Critical Components:<\/strong> Avoid lazily loading critical components that are essential for the initial render.<\/li>\n<li><strong>Cache Management:<\/strong> Consider cache management strategies for lazy-loaded modules to improve load times during subsequent visits.<\/li>\n<\/ul>\n<h2>Conclusion<\/h2>\n<p>Code splitting is a crucial optimization technique that every React developer should be familiar with. By utilizing <strong>React.lazy<\/strong> and <strong>React.Suspense<\/strong>, you can significantly enhance the load time and performance of your React applications. As web applications continue to grow in complexity, implementing these performance best practices will contribute to a better user experience.<\/p>\n<p>Start exploring code splitting in your projects today and witness the performance improvements firsthand!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Code Splitting in React with Lazy &amp; Suspense React has gained immense popularity due to its component-based architecture, which allows developers to build efficient and scalable user interfaces. One technique that further enhances performance in React applications is code splitting. This post delves into code splitting using React.lazy and React.Suspense, two powerful features introduced in<\/p>\n","protected":false},"author":77,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[398],"tags":[224],"class_list":["post-7583","post","type-post","status-publish","format-standard","category-react","tag-react"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/7583","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/users\/77"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=7583"}],"version-history":[{"count":1,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/7583\/revisions"}],"predecessor-version":[{"id":7584,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/7583\/revisions\/7584"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=7583"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=7583"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=7583"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}