Route based Code Splitting with React Router

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everyone in this video let's go over the concept of route based code splitting in a react application if you're getting started with react and trying to build a medium to large scale application this video will benefit you from a performance optimization point of view to be more specific this video will help you understand one of the ways to optimize the initial load time of your application we're going to go over what is code splitting how to lazy load routes with react lazy and react router and how to use react suspense to render a fallback ui when lazy loading components all right let's begin by understanding what is code splitting traditionally all the components in the react application would be bundled into one single file called bundle.js this allows the browser to download the entire app once so that the user can navigate seamlessly without having the need to make another http request to the server while this was helpful it did have a drawback as the application grew in size and more third-party packages were installed the bundle size bloated up causing the app to have a long initial load time so there was a need to solve this problem of having one bundle with a large file size to address this drawback code splitting was identified as a solution as the name indicates a single bundle file is split into smaller ones and the user will only download the code that they need you can think of code splitting as incrementally downloading the application and if you think about it the user shouldn't have to download your entire application when all they need is a part of it for the initial landing page of course it can also be navigation beyond the landing page for example with an analytics website if a user wants to navigate to their profile page and then log off there is no need to download the bulky code related to the dashboard page where all the data visualization code is present it's wasteful and certainly doesn't help people who have a limited bandwidth to work with the good news is that create react app with its webpack config supports code splitting out of the box now to get us started i have already set up the necessary code let me go over the different files in the components folder we have three components home component with some basic jsx with some basic jsx again and then we have the dashboard component this dashboard component imports the react plotly package react plotly is basically a third-party package for data visualization of course you might not be using this exact package in your app but the package is bulky and serves the purpose of helping us understand code splitting and lazy loading in a react application the dashboard component as you can see here renders a simple chart in app.js we have imported the necessary components from react router and setup the app routing configuration we have home component which navigates to just the root of the application slash profile we render the profile component slash dashboard we render the dashboard component we also have three links to navigate to each of the three routes now if we start this application and take a look at the browser we have the home page the profile page and the dashboard page a simple app with three routes let's go back to vs code and take a look at the build output by running the build command in the terminal so in the terminal run the command yarn build once the build completes create react app gives us a snapshot of the files emitted and their file size you can see that we have five different files let's go bottom up the main dot hash dot chunk dot css represents all the css code our application needs the main dot hash.chunk.js represents our application files like app.js home.js profile.js etc so the code we have written for our application we then have runtime main.hash.chunk.js which represents a small webpack runtime logic used to load and run our application finally we have these number.hash.com like two dot and three dot which represent all the libraries used in our application basically the code imported from node modules so the production build as you can see is optimized we do have our code split into five different files but when we load our application in the browser all these chunks are still loaded anyway let me quickly show you that to run the built app navigate into the build folder cd build and run the command npx serve the app should be running on localhost port 5000. if i open the network tab and empty the cache and reload you can see the various resources that are fetched our focus is on this particular chunk the two dot hash.chunk.js file which is 1.1 mb this chunk basically refers to the third-party package we have installed which is the blockley.js library and as you can see it is quite big in size but here's the thing when we are hitting the home page we are fetching the code related to the dashboard page this is adding an additional 237 milliseconds into the load time and we have already spoken about the solution the solution is to load only the code needed for the home page and then asynchronously fetch the code for other routes when the user navigates to those pages let's see how to achieve that with react and react router step one we are going to dynamically import the profile and dashboard components using react lazy and dynamic imports which is a modern javascript feature so comment out the import statements for profile and dashboard instead we use react lazy and dynamic imports so const lazy profile is equal to react dot lazy and lazy is a function that takes another function as an argument this argument calls a dynamic import we specify the path to the profile component components slash profile a promise is returned by this dynamic import which is then converted into a module that contains a default export react component so our lazy profile now refers to the profile component but it is lazy loaded i'm going to make a copy of this for the dashboard component as well so that is our step one step two we include the lazy components as part of the route configuration so instead of profile lazy profile and instead of dashboard lazy dashboard let's now save the file and rebuild our application yarn build npx serve again and if i now empty cache and hard reload you can see in the network tab the 1 mb chunk is not present anymore and we have improved our initial load time however there is a problem if we try to navigate to either profile or dashboard we're going to see an error in the console a react component suspended while rendering but no fallback ui was specified to fix this error we have to use the suspense component from react so back in app.js i'm going to wrap all the routes with react dot suspense and we specify the fallback prop now the fallback can be any react element but i'll just leave it as a string loading let's save the file rebuild the application navigate inside the build folder again and run npx serve if you now go back to the browser home page empty cache and hard reload the 1mb chunk is still not loaded now if i clear the network tab navigate to the profile page you can see that a new chunk of code is downloaded this chunk corresponds to the profile component if i now clear the network tab again and navigate to the dashboard page we see the loading text in the browser and then the dashboard component is rendered dynamic imports are asynchronous and hence the loading fallback is rendered while the resource is downloaded in the background so you can observe again let me go back home empty cache and hard reload and observe the loading text when i navigate to the dashboard page loading and then the dashboard component is rendered let's also focus on the network tab so go back home empty cache and hard reload navigate to the dashboard page you can see two more chunks are downloaded 800 bytes and 1 mb which correspond to the dashboard component code and the chart library we are using so this is pretty much how you can achieve route based code splitting to optimize the initial load of your react application while you haven't reduced the overall amount of code in your app you've avoided loading code that the user may never need and reduce the amount of code needed during the initial load now dynamic imports react lazy react suspense were all topics that i wanted to cover as part of the react router series but i guess with me deferring to create the series till react router version 6 is release this video has taken ahead but hopefully better late than never and you now have an idea on how to improve the initial load time of your application thank you guys for watching make sure to subscribe to the channel and i'll see you guys in the next one
Info
Channel: Codevolution
Views: 11,296
Rating: 4.9774013 out of 5
Keywords: Codevolution, React, React Router, React.lazy(), React Suspense, Dynamic Imports, React Dynamic Imports, Code Splitting, Code Splitting in React, Route based Code Splitting with React Router
Id: 5ZFK_5V8VpI
Channel Id: undefined
Length: 12min 41sec (761 seconds)
Published: Sun Apr 11 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.