Speed Up Your React Apps With Code Splitting

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
if your react app is loading slowly one of the easiest ways you can speed that up is with code splitting in this video I'm going to be covering what code splitting is when to use it how to use it and any pitfalls that you may run into when it comes to code splitting so this is the complete guide that you need for code splitting [Music] welcome back to web dev simplified my name is Kyle and my job is to simplify the web for you so you can start building your dream project sooner and to get started here I have a really simple react application as you can see I have a router set up using react router and we just have three different routes inside this nav wrapper and all this nav wrapper does is display our navigation and then it just shows whatever our page is so we have a home page we have a store Page and an about page and on the right hand of my screen you can see we're on our home page our store Page here just has an empty store Page same with our about page and our home page has some content so if we go to that home page you can see all that this page is doing is we have a simple state for is admin or not which we toggle whenever we click on this toggle admin button then on our other button we click and it's just going to add two plus two and alert to us four and then as you can see down here depending on if we're an admin or not we're showing that admin data which is just really simply one single string of text or we're showing this not admin text now the whole idea behind code splitting is that instead of loading your entire application at once it's going to split out the different parts of your application and only load them when you need them so for example if I refresh my page here I'm on the home page so there's no point in me downloading the store Page or it'd be downloading the about page because I'm not actually on those pages yet also this sum function that I call right here to add the numbers two and two together there's no point in me downloading that code until I actually click the button to add those numbers together so the idea of code splitting is making sure you only download the code as soon as you need it now if I just give the page a quick refresh and I just do an inspect on the page this is going to be a fresh load of everything that gets downloaded as soon as I access this page if I go to the sources tab we can actually view all of the code that's being downloaded and the best thing that we can do is actually look over here on the left hand side where we have the file system essentially if we go into this Source folder you can see here we have our actual code and as well as our components folder and our client and so on but the main thing you'll notice is that inside of here all of the files inside of our components being loaded so if you look here we have our about our admin data our home our store we have here our sum being downloaded every single file in our project all of these files are being downloaded on the very first load of the page while we're not actually accessing our store or our about so we should want to delay those files from being downloaded until we go to access those pages this becomes especially useful as your project starts to get larger and larger because if you download the entire file structure for the entire application at once it's going to take a very long time so splitting that up is going to be very beneficial so the easiest way to do code splitting is if you just want to code split out a simple function for example this sum function right here I'm going to show you first how to do that and then I'll show you how to code split out individual components so in order to code split something we can use a dynamic import and a dynamic import is going to only import the code when we actually use it on the page so for example here instead of importing my sum function up here I'm going to remove that import and instead I'm going to import it right here whenever I click on the button so let's just put this on another line so it's a little bit easier to read and what I want to do is I want to use import but I'm going to call it as a function I want to pass it the path to that file so in our case it's just dot dot slash sum just like that and we'll just put the dot JS at the end there so then we can do is we can just say dot Ben this returns to us a promise and that promise is going to have our module object inside of it this module object is going to have a bunch of different properties so like module.default that's going to be the default export in our case this sum is not a default export so we can say module.sum and that's going to access the named export which we called sum if we had another export called like two that is going to be just accessed like this so we can say dot sum we can put our numbers 2 and 2 in there and if we just do a simple alert where we are alerting that out so it works just like it was before now when we click on our button it's going to download the file for our sum.js and it's going to alert out that value so let's do a really quick example of that if I refresh my page and I click the sum button you can see everything works exactly the same as before let's do another refresh so we have a completely fresh load of our application if I go over to that sources tab you'll notice inside of here are some.js file is not actually loaded yet but as soon as I click on that button you'll notice over here on the left hand side of my screen that some js file has been downloaded onto the page and it's actually running to do that summing so it's not actually running or downloading that code until I actually need it which is where code splitting comes in and this is great for individual functions like this sum function but where this becomes really useful is for code splitting out your different components and react has a tool called react.lazy which makes this incredibly easy now probably the number one place that you're going to be wanting to do this code splitting is going to be inside of your router obviously if you're on your home page there's no point downloading the store or the about components and that's going to save you a lot of time because just downloading one page is much quicker than downloading three or hundreds or thousands of pages so to do this code splitting we're going to remove our normal import statement and we need to do a dynamic import so we know that this is going to be an import where we call a function and we pass it in our path which is in our case our home file like this but to do this with a component inside of react we need to use react.lazy so we can say react dot lazy or if you don't want to call react.lazy like that you can just import the lazy method up here from react and then it's going to work just like this so inside of this lazy method you pass it a function and this function right here all it needs to do is return a promise which is this import statement so we do our import this returns to us a promise and then this right here is going to return to us a variable we can use exactly the same as our normal component we imported so if I save you'll notice if I just do a refresh over here everything looks exactly the same as before if I go to my store Page and do a refresh that's simulating me coming to the site directly on the store Page you'll notice if I go over to that sources tab real quick I just close out of everything and we look inside of our components the home page component is not being downloaded yet and as soon as I click on that home page button you'll see now all the information from my home page including that admin data component are all being downloaded after the fact so I'm only downloading the components when I need them you will notice a bit of an error though in that none of our content is actually showing up if I do a refresh you'll see the content shows up but it's not showing up when I click on that link for the very first time the reason for that is when you're using this lazy loading of components react needs to to know that you're lazy loading different things and you need to use suspense to do that so we're going to be importing suspense from react and I'll show you exactly how this works and why it works like it does so this is just a fancy component inside react and what you want to do is you want to wrap whatever is going to be lazy loaded inside that suspense so this Outlet right here just renders whatever our route is in our case our home page our store Page or our about page so we can just wrap this Outlet inside of this suspense component and now if we do that we're telling react everything inside of here has the potential to be lazily loaded which means it might not be available right away in our case when we click on the home link we're going to downloading this home component and then rendering it when it's finished so if it's a large component or maybe your internet is really slow this might take a while which is why the suspense component has this fallback feature and whatever you put in here it can be a component it can be text whatever you want we'll just put like an H1 that says loading whatever you put inside of here is going to be rendered instead of the actual content that is right here so while this home page is being downloaded it's going to say loading on the screen and then once it's downloaded it's going to show that normal content so let's go over to our store Page do a refresh to simulate what happens when we click on home and you'll notice for a brief millisecond it says loading dot dot dot now obviously my internet is quite fast and I'm only downloading this file locally so it's going to be incredibly quickly but if we had a much slower loading time this would be a loading screen that would show for quite a while this is actually something we can fairly easily simulate I'm just going to really quickly create a dummy function this function is called weight and all it does is it waits until a set timeout is complete so what I can do up here is I can call weight with a thousand and then just say dot then and then actually returned the value for this import here all this code is doing is the same wait a thousand seconds before doing my import so it's simulating what a slow connection would look like so now if I just go over my store Page do refresh here click on home you'll notice it says loading for one second before my actual content shows up so if this was a slower internet connection or maybe you downloaded a large file you can kind of see what that would look like and that's what this weight function is just simulating so it shows the fallback and then it shows the content once it's downloaded now doing this for our store Page is going to be the exact same process I'm just going to copy this all down we're going to say store right here and we're going to import that from store just like that and we're going to comment this out and you'll notice that switching between these views works exactly the same and something else that you'll notice is when I go back to my store Page you'll see that there's no loading that happened same thing back to home the reason for that is I've already downloaded that component into my browser so it doesn't need to re-download it once you download it once it doesn't need to download any more times now we will run into a problem when we get to this about component though if we just copy this down I placed an about here change this to about and I do a save you're going to notice boom we're automatically getting a bunch of Errors the reason for that is if we look at my home component my store component they're exporting default functions while my about component is exporting a named function and the way that this lazy import works is it expects you to return something that looks like this where it has a default and then this is going to be you know your component so it expects you to return an object that has a default property and then it has an actual component in that property so with all of our normal module Imports that works just fine because when you do a dynamic import you're going to get a return that looks like this so for example you have your default and that's going to be your component and then if you have a named export like about it's going to be you know something that looks like this so by default all of these that have default exports are going to work just fine but our named exports don't work quite like we would expect so in order to fix that we can do a little bit of tweaking what I'm going to do is I'm just going to remove this so it's a little bit easier to read what's going on get this back to just a really simple normal import whoops there we go and what I want to do is I just want to say dot then I don't want to actually get my module that's being returned to me and my module here like I mentioned has that about property so we can say we want to return a property that is default and we're just going to set that to our module dot about all that this is doing is essentially renaming our import so that instead of being at dot about it's at that dot default and that little change right there is all we need to do to make this work we just give this a quick refresh here you notice it's still not quite working that's because I forgot to comment this section out up here now if I save you'll notice that it is working just fine when we go to that about page and just to prove that it wasn't working before I'll remove all the code I added click save do a refresh and you'll see that the about page doesn't show up so there is an error if we don't do it like we expected now if we put it back you can see that it works now this may be the most common way that you would do code splitting by doing it based on your pages but a lot of times you may have content on your page which is only applicable to certain users for example on our homepage we have this section for our admin data and imagine this is like a crazy big admin dashboard that shows up for admin users and for normal users it doesn't show up so it's a very large amount of data that's being downloaded what you wouldn't want to show all of that data every single time any user went on the page even if they don't have access to it there's no need to download that information so we can again use code splitting to make sure we only show that information if this person is an admin so instead of doing our normal import like this let's do it the react lazy way so I'm just going to copy over this code exactly from our about here I'm going to paste it down because this is a named export so we're going to call it admin data it's coming from our admin data component and here we're getting our admin data that right there gives us the admin data itself and it's being lazy loaded all we need to do is wrap this inside of a suspense so here we can say suspense just like that give it a fallback fall back is equal to let's just say loading let's make that an H2 just so it matches up with the other content in that section and now if I give this a quick save and I click toggle admin you should see it would show the loading text but this is way too fast let's slow it down with that artificial weight just so we can see what would happen so I'm going to paste that function down and up here I'm just going to do a simple weight dot or a weight for a thousand so that's one second and then we're going to call this import right here there we go so now let's just do a quick refresh you can see it's loading my home page and we're getting an error the reason is is we need to make sure that we import lazy and suspense so let's just import both of those and now hopefully if we give this a refresh it should work and there we go you can see it's working now when I click toggle admin that's going to make my admin true which means we're going to show this admin data which is being lazy loaded so it should show us the text loading as you can see it shows the text loading and then it says you are an admin and now I can toggle between the two with no problem so if you're a non-admin user it's never going to download this content because it doesn't need it but if you are an admin user it'll download it when the page loads and it'll give you a loading bar now the last thing I want to talk about when it comes to Lazy loading is what happens when you don't actually want to show a fallback state so for example normally we have this loading text that shows up when we change between these things but what happens if you have like tabs on a system and you want to just keep the old data there until the new data is finished loading this is a fairly common use case well to do that in react we need to use the use transition hook now this is a hook that I have an entire video on I have an entire course actually on all the hooks I'll link it down in the description for you if you want to learn more about how this hook works but essentially it allows us to do non-urgent updates which won't change our UI until they're finished updating so what we can do is we can just make sure we call that hook and that hook is going to return to its two values the first is going to be is pending which we don't actually care about and then we can have a start transition which is the thing that we care about because that allows us to do this update just call that hook there we go and now what I want to do is when I click on this button here to set is admin instead I want to put that inside of a transition so I'm going to bring this onto a new line just to make it easier to read I'm going to call start transition and this just takes a single function and inside here is where we put our updating for our state so now what's going to happen is my actual UI is not going to do this fallback value because my UI is not going to update until this transition is finished which means it's going to wait for this entire thing to download before it tries to show any data at all so when I click toggle we'll just do a refresh first when I click on this toggle button you'll notice my UI doesn't change until after everything's loaded so I don't get that loading state but I can use this is pending variable to show some type of loading state if I wanted to for example I could just say is pending and what I could do is I could just say loading really straightforward stuff like that so now let's just give this quick refresh and click toggle admin you can see it's saying loading and then it shows up right there you could use this for example to like blur out the background and show like a giant loading spinner over top of everything if you wanted that's a much cleaner way than just blinking out everything and showing like the text loading for example now the very last thing I actually want to talk about is if you're doing a lot of deep or named exports like this it's kind of cumbersome to write out your Imports like this every single time so actually I recommend just creating like a really simple function we'll just call this lazy load dot JS I'll just paste the code in here essentially all this code does right here we'll get rid of the weight because that's not actually part of it all this code is doing is it's making it so you can call Lazy load you can pass it the path to your component for example let's say slash components slash about and then we can say that this is an about named component this is going to allow you to import something that has the name of about from this actual URL and that's really great if you don't use default exports for example I almost always use named exports like this so having this little handy function makes importing these things with react.lazy a lot easier as you can see the code just calls that lazy function from react it gets a promise for my import if we have the named path so for example if you don't pass in a path it just gives you the default export like normal otherwise if you do pass in a path what it's going to do is just going to take that path name and set it as the default so react knows what to do with it so for example what I can do is I could just take this go back over to my home change all of this code here to just say that we want to do a lazy load we want to get it from components slash admin data and our thing here is called admin data let me just make sure I import lazy load just like that so now if I save give my page a refresh it should work exactly the same as before as you can see it's toggling just fine we have that slight loading State showing up because this is doing it essentially instantaneously now the only thing to be aware of with this is all of your past that you're going to be passing for your import are relative to wherever you define your lazy load function and not relative to where the actual file is that you're doing the import that's the only thing you need to take into account when using this approach and that's everything you need to know about code splitting in react if you want to Deep dive into that use transition hook or any other react hook I highly recommend checking out my completely free react hook simplified course it's linked down in the description below with that said thank you very much for watching and have a good day
Info
Channel: Web Dev Simplified
Views: 334,607
Rating: undefined out of 5
Keywords: webdevsimplified, react, react js, react javascript, react js code splitting, code splitting, react lazy, react.lazy, react js lazy, react javascript code splitting, react code splitting, javascript code splitting, js code splitting, react.lazy splitting, react lazy js
Id: JU6sl_yyZqs
Channel Id: undefined
Length: 16min 49sec (1009 seconds)
Published: Sat Dec 10 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.