

{"id":114120,"date":"2023-06-20T09:00:39","date_gmt":"2023-06-20T03:30:39","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=114120"},"modified":"2023-06-20T18:19:02","modified_gmt":"2023-06-20T12:49:02","slug":"react-code-splitting","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/react-code-splitting\/","title":{"rendered":"React Code Splitting"},"content":{"rendered":"<p>Code splitting is a technique used in React to improve the performance and load times of web applications. It involves splitting a large bundle of code into smaller, more manageable chunks that can be loaded on demand.<\/p>\n<p>The concept of code splitting has become more relevant as web applications become more complex and larger in size.<br \/>\nBy splitting code into smaller chunks, the initial load time of the application is reduced.<\/p>\n<h3>Benefits of Code Splitting in React<\/h3>\n<p>The main benefit of code splitting is improved performance. When an application is first loaded, all of the code is loaded at once, which can cause the application to be slow and unresponsive. By splitting the code into smaller chunks, it reduces the load time and improves performance.<\/p>\n<p>Another benefit of code splitting is improved maintainability. When code is split into smaller chunks, it becomes easier to manage and maintain. This is especially true for larger applications, where managing a large codebase can be a challenge.<\/p>\n<h3>Implementing Code Splitting in React<\/h3>\n<p>React provides several built-in mechanisms for code splitting. The most commonly used method is dynamic import(), which allows you to load a module on demand. Dynamic import() returns a promise that resolves to the module, which can then be used in the application.<\/p>\n<p>Here is an example of how dynamic import() can be used to load a component on demand:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import React, { lazy, Suspense } from 'react';\r\n\r\nconst MyComponent = lazy(() =&gt; import('.\/MyComponent'));\r\n\r\nfunction App() {\r\nreturn (\r\n&lt;div&gt;\r\n&lt;Suspense fallback={&lt;div&gt;Loading...&lt;\/div&gt;}&gt;\r\n&lt;MyComponent \/&gt;\r\n&lt;\/Suspense&gt;\r\n&lt;\/div&gt;\r\n);\r\n}<\/pre>\n<p>In this example, the MyComponent module is loaded on demand using dynamic import(). The lazy() function creates a new component that loads the module when it is needed. The Suspense component is used to show a loading message while the module is being loaded.<\/p>\n<h3>Implementing React code splitting using webpack bundler<\/h3>\n<p>Another method for code splitting in React is using the webpack bundler, which is the default bundler for Create React App. webpack supports a feature called &#8220;code splitting&#8221; that allows you to split your code into smaller chunks. You can configure webpack to split your code based on different criteria, such as entry points or routes.<\/p>\n<p>Here is an example of how code splitting can be configured in webpack:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">const path = require('path');\r\n\r\nmodule.exports = {\r\nentry: {\r\nmain: '.\/src\/index.js',\r\n},\r\noutput: {\r\nfilename: '[name].[contenthash].js',\r\npath: path.resolve(__dirname, 'dist'),\r\nclean: true,\r\n},\r\noptimization: {\r\nsplitChunks: {\r\nchunks: 'all',\r\n},\r\n},\r\n};<\/pre>\n<p>In this example, webpack is configured to split the code based on all chunks. This means that webpack will automatically split the code into smaller chunks based on the dependencies between the modules.<\/p>\n<h3>Route-based code splitting<\/h3>\n<p>Route-based code splitting is a technique used in modern web development to optimize the performance of web applications. It involves breaking down large codebases into smaller, more manageable chunks.<\/p>\n<p>Route-based code splitting solves this problem by allowing developers to divide the application into smaller pieces.<br \/>\nFor example, if the user navigates to a page that requires a specific module or component, that module or component is loaded dynamically without the need to load the entire application codebase.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">const { lazy, Suspense } = React;\r\nconst { BrowserRouter: Router, Switch, Route, Link } = ReactRouterDOM;\r\n\r\nconst HomePage = lazy(() =&gt; import('.\/components\/HomePage'));\r\nconst AboutPage = lazy(() =&gt; import('.\/components\/AboutPage'));\r\nconst ContactPage = lazy(() =&gt; import('.\/components\/ContactPage'));\r\n\r\nfunction App() {\r\nreturn (\r\n&lt;Router&gt;\r\n&lt;div&gt;\r\n&lt;nav&gt;\r\n&lt;ul&gt;\r\n&lt;li&gt;&lt;Link to=\"\/\"&gt;Home&lt;\/Link&gt;&lt;\/li&gt;\r\n&lt;li&gt;&lt;Link to=\"\/about\"&gt;About&lt;\/Link&gt;&lt;\/li&gt;\r\n&lt;li&gt;&lt;Link to=\"\/contact\"&gt;Contact&lt;\/Link&gt;&lt;\/li&gt;\r\n&lt;\/ul&gt;\r\n&lt;\/nav&gt;\r\n&lt;Suspense fallback={&lt;div&gt;Loading...&lt;\/div&gt;}&gt;\r\n&lt;Switch&gt;\r\n&lt;Route exact path=\"\/\" component={HomePage} \/&gt;\r\n&lt;Route path=\"\/about\" component={AboutPage} \/&gt;\r\n&lt;Route path=\"\/contact\" component={ContactPage} \/&gt;\r\n&lt;\/Switch&gt;\r\n&lt;\/Suspense&gt;\r\n&lt;\/div&gt;\r\n&lt;\/Router&gt;\r\n);\r\n}\r\n\r\nReactDOM.render(&lt;App \/&gt;, document.getElementById('root'));<\/pre>\n<p><strong>Output (after clicking on about)<\/strong><\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/04\/rout-based-code-splitting.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-114141\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/04\/rout-based-code-splitting.png\" alt=\"route based code splitting\" width=\"542\" height=\"203\" \/><\/a><\/p>\n<h3>React Error Boundaries:<\/h3>\n<p>React Error Boundaries are components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed. These are React components that catch errors in their child component hierarchy, log those errors, and display a fallback UI. Error boundaries can only catch errors that occur during rendering, in lifecycle methods, or in constructors of the whole tree below them.<\/p>\n<p>Error boundaries are a helpful tool when it comes to code splitting because they allow you to handle errors that might occur when loading certain parts of your application asynchronously. With error boundaries, you can ensure that your application doesn&#8217;t completely break when errors occur during code splitting.<\/p>\n<h3>React Named Exports:<\/h3>\n<p>In React, code splitting can be achieved using dynamic imports. Dynamic imports allow you to import a module only when it&#8217;s needed, rather than loading it with the rest of your application. This can help reduce the initial load time of your application and improve its performance.<\/p>\n<p>Named exports, on the other hand, are a way to export specific functions, variables, or classes from a module. When you use named exports, you can import only the parts of a module that you need, rather than importing the entire module. This can help reduce the size of your application, which can improve its performance.<\/p>\n<p>Named exports are particularly useful when you&#8217;re working with code splitting because they allow you to import only the parts of a module that you need. This can help reduce the amount of code that&#8217;s loaded upfront, which can help improve the initial load time of your application.<\/p>\n<h3>Conclusion<\/h3>\n<p>Code splitting is an essential technique for improving the performance and maintainability of React applications. By splitting the code into smaller chunks, you can reduce the load time of the application. React provides several built-in mechanisms for code splitting such as dynamic import()<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Code splitting is a technique used in React to improve the performance and load times of web applications. It involves splitting a large bundle of code into smaller, more manageable chunks that can be&#46;&#46;&#46;<\/p>\n","protected":false},"author":581,"featured_media":114122,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[27227],"tags":[27483],"class_list":["post-114120","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-react-tutorials","tag-react-code-splitting"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v28.0 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>React Code Splitting - DataFlair<\/title>\n<meta name=\"description\" content=\"Code splitting is an essential technique for improving the performance and maintainability of React applications. Learn more about it.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/data-flair.training\/blogs\/react-code-splitting\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"React Code Splitting - DataFlair\" \/>\n<meta property=\"og:description\" content=\"Code splitting is an essential technique for improving the performance and maintainability of React applications. Learn more about it.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/react-code-splitting\/\" \/>\n<meta property=\"og:site_name\" content=\"DataFlair\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/DataFlairWS\/\" \/>\n<meta property=\"article:published_time\" content=\"2023-06-20T03:30:39+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-06-20T12:49:02+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/04\/react-code-splitting.webp\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/webp\" \/>\n<meta name=\"author\" content=\"DataFlair Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:site\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"DataFlair Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"5 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"React Code Splitting - DataFlair","description":"Code splitting is an essential technique for improving the performance and maintainability of React applications. Learn more about it.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/data-flair.training\/blogs\/react-code-splitting\/","og_locale":"en_US","og_type":"article","og_title":"React Code Splitting - DataFlair","og_description":"Code splitting is an essential technique for improving the performance and maintainability of React applications. Learn more about it.","og_url":"https:\/\/data-flair.training\/blogs\/react-code-splitting\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2023-06-20T03:30:39+00:00","article_modified_time":"2023-06-20T12:49:02+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/04\/react-code-splitting.webp","type":"image\/webp"}],"author":"DataFlair Team","twitter_card":"summary_large_image","twitter_creator":"@DataFlairWS","twitter_site":"@DataFlairWS","twitter_misc":{"Written by":"DataFlair Team","Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/react-code-splitting\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/react-code-splitting\/"},"author":{"name":"DataFlair Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/c187795dc82ab948373cca526df7c445"},"headline":"React Code Splitting","datePublished":"2023-06-20T03:30:39+00:00","dateModified":"2023-06-20T12:49:02+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/react-code-splitting\/"},"wordCount":794,"commentCount":0,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/react-code-splitting\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/04\/react-code-splitting.webp","keywords":["React Code Splitting"],"articleSection":["React Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/react-code-splitting\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/react-code-splitting\/","url":"https:\/\/data-flair.training\/blogs\/react-code-splitting\/","name":"React Code Splitting - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/react-code-splitting\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/react-code-splitting\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/04\/react-code-splitting.webp","datePublished":"2023-06-20T03:30:39+00:00","dateModified":"2023-06-20T12:49:02+00:00","description":"Code splitting is an essential technique for improving the performance and maintainability of React applications. Learn more about it.","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/react-code-splitting\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/react-code-splitting\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/react-code-splitting\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/04\/react-code-splitting.webp","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/04\/react-code-splitting.webp","width":1200,"height":628,"caption":"react code splitting"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/react-code-splitting\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog Home","item":"https:\/\/data-flair.training\/blogs\/"},{"@type":"ListItem","position":2,"name":"React Tutorials","item":"https:\/\/data-flair.training\/blogs\/category\/react-tutorials\/"},{"@type":"ListItem","position":3,"name":"React Code Splitting"}]},{"@type":"WebSite","@id":"https:\/\/data-flair.training\/blogs\/#website","url":"https:\/\/data-flair.training\/blogs\/","name":"DataFlair","description":"Learn Today. Lead Tomorrow.","publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/data-flair.training\/blogs\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/data-flair.training\/blogs\/#organization","name":"DataFlair","url":"https:\/\/data-flair.training\/blogs\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","width":106,"height":48,"caption":"DataFlair"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/DataFlairWS\/","https:\/\/x.com\/DataFlairWS","https:\/\/www.linkedin.com\/company\/dataflair-web-services-pvt-ltd\/","https:\/\/www.youtube.com\/user\/DataFlairWS"]},{"@type":"Person","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/c187795dc82ab948373cca526df7c445","name":"DataFlair Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","caption":"DataFlair Team"},"description":"DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.","url":"https:\/\/data-flair.training\/blogs\/author\/dfteam6\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/114120","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/users\/581"}],"replies":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/comments?post=114120"}],"version-history":[{"count":3,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/114120\/revisions"}],"predecessor-version":[{"id":114142,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/114120\/revisions\/114142"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/114122"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=114120"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=114120"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=114120"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}