Speed Up Your React Apps With Code Splitting
HTML-код
- Опубликовано: 14 май 2024
- FREE React Hooks Simplified Course: courses.webdevsimplified.com/...
Performance is something people always worry about, especially in React, but oftentimes the bundle size of an application is ignored when doing performance optimization. In this video I want to talk about how you can minimize the bundle size of your application by using code splitting to only download the code you need when you need it.
📚 Materials/References:
FREE React Hooks Simplified Course: courses.webdevsimplified.com/...
🌎 Find Me Here:
My Blog: blog.webdevsimplified.com
My Courses: courses.webdevsimplified.com
Patreon: / webdevsimplified
Twitter: / devsimplified
Discord: / discord
GitHub: github.com/WebDevSimplified
CodePen: codepen.io/WebDevSimplified
⏱️ Timestamps:
00:00 - Introduction
00:25 - Setup
01:11 - What Is Code Splitting
02:39 - Code Splitting A Function
04:30 - Code Splitting Components
10:40 - Conditional Code Splitting
12:52 - Advanced Code Splitting Concepts
#React #WDS #CodeSplitting
7:53 You can always simulate slow connections via Web Console > Network > throttling > Slow3G
I was wondering why he didn't do that also because he's already used it in videos such as ruclips.net/video/ZVug65gW-fc/видео.html
@@pearl911 I'd say using a wait function makes the wait time more deterministic. And you can change the wait time to however long you want.
Thought the exact same thing. Best part IMO of the network tab is the ability to set a custom TTFB which is a very real and practical scenario to test.
Kyle showed an example of a useful Promise 😉
That is pretty useful, but for what it's worth doing this particular task with dev tools throttling would have required waiting much longer for react itself to download than for the component to download... the way he did it was actually a lot better for the demonstration.
Asynchronous imports aren't just a cheat code to making your app faster. You should only use it if there are portions of the app that are not needed until the user initiates some process. For example if some component is hidden until the user clicks a button, then you could asynchronously import that component.
There is also a prefetch variable for webpack which download that resource when the engine is idling. It is not quite the same situation but i wanted to point that out
Like lazy loading in angular?
@@gabrielemarino1360 this should be better, let the engine do the job for u
And why would you not load portions of the app that are not needed yet? Why not just load them from the beginning? To make the app faster, genius.
@@Cotita yes but my point was that it's important to know how and why to use this feature. Just throwing around async imports everywhere isn't necessarily going to improve anything.
That's the best thing ever. I didn't even think that this could be a thing in React at all. Thanks for making this video! 💕
The quality of these vids has gone way up over the years man! Well spoken.
At 07:52 To depict Loading... you don't need to add wait. You can simply open up your console, Go into Network Tab. In the bottom layer, you'll see "No throttling", click that and change it to "Slow 3G" and there you go. You can actually see how your fallback will work when there is a delay in your network.
I always wait for your content about React JS. Thank you for the knowledge 🙏
I watched this lesson 2 month ago, but always try to revise your videos. Thanks!
I loved this video. I understood way better the concept of code splitting. I can now apply this knowledge, Thank you very much Kile😁
Great video as always! Keep it up, you're an essential instructor in the Javascript ecosystem 😎
Man, you are a true hero! Thank you very very much for the amazing content!
Please bring more videos related to performance improvement, aria, testing related, logging, debugging issues, improving css loading time etc
this guy is a busy guy bro, probably has a full time dev job, he runs his own business and he makes videos, 😂, work ethic i aspire to have
Great video clear explanation and example as usual ⭐
Always things i've never heard about before. Great stuff!
I was waiting for your new video, hanging around the playlist section .
Great as always. Thank you, Kyle!
In the lazyLoad function, you don’t really need an else statement since you’re returning from the if. Without an else that would be an else regardless. I know some people prefer verbosity, but that’s actually confusing for some. Great video regardless, you’re a very good communicator!
Simply WOW , this may super useful when we working on complex applications
Great video Mr. Simplified. Thank you!
Kyle, this is a great video. However, I think there are a few additions that would've made it better:
1) In addition to showing files being downloaded piece by piece, demonstrating this using network tab in the dev console would've also be a great way to show people how to also make the most out of the dev console by debugging network latency, Showing them that you're downloading the entire client app in one go versus downloading it bit by bit as the user uses the site over time.
2) Another dev console trick would've been to demo the way emulation of 4g internet works by using the throttling feature in the network tab as well. That wait function is pretty cool but these tools were built for developers in mind.
3) Finally, if you added a build script and built the app, showing people how the bundle was created as just one large js file before lazy loading but after adding lazy loading, it bundles itself into multiple smaller bundles.
"multiple smaller bundles" - a.k.a. chunks
3 was really missing!
thanks :)
Nice suggestions indeed!
Great suggestions!
Nicely done friend. I learn so much from your videos. Thank you.
Learn so many stuff in just 15 mins, thanks a lot.
Great video, thank you. Splitting stuff into more bits is not just making app faster, but its also good for separation of concerns.
I was struggling with permission based access for the user in my app.
Things weren't working very well.
Now, I think things will be fine when I use the useTransition hook.
Great!
Explained perfectly. Thank you
This is really helpful , thank you!
thankyou for this useful information really appreciate you for this.
Great video clear explanation and example as usual
Good God, finally a valid explanation of this topic. Thanx a lot sir.
Great Explanation Bro
Great video. You can use both default and named export at the same time, so technically you can use default for the main component that needs to be loaded in the route. I always use both!
indeed, I always use the way like that,
If i use default should i adding second paraneter in lazyload function?
Have learned a lot from you bro, ❤️ from Bangladesh
I don't know why but somehow I can understand your video with my not really good English. Thank you so much mate !😁
Nice, ive learn something new. Good job
Informative concept. Thanks
Thanks for this video. Design is very human, easy to use) Thanks ❤
You are incredible thx for the video ❤
Thank you, this is a great feature of React that I wasn't aware of.
But when using TypeScript, passing the path to the component into your lazyLoad function doesn't work.
But if I changed the lazyLoad function to accept a Promise, then pass into it the import('...') and then the namedExport, it works fine.
tnx for your tipe's bro
Very useful tutorial! Thanks
Very useful and clear!
That's interesting. Qwik is doing something like this. It listens to the global window object then brings in the data when there are actions. It could certainly help bring code down on first load.
as always, great video 👍
I think it's important to note that the helper function at 15:06 will not work in production builds depending on the build tool you're using because the transpiler can't guess ahead of time what you're going to import through that function (Vite even warns you about that). I tested it with Vite + TypeScript (no SWR) and while it does work fine in dev mode, it will not work in production mode. The transpiler doesn't create the imported JS files in the destination directory and the app will try to dynamically import "/assets/components/Something(.js/.ts)" which obviously doesn't exist. Unfortunately, I don't think there's a workaround for this in JS alone, but there could be build plugins for it.
which means you are expected to leave your code un-bundled as if in dev mode if you are going to use this dynamic import cheat.
100% this answer. When you run a large app, the last thing you want is failed to load dynamically imported module clogging up your logging and getting calls from your Bridge.
Just pass the import("whatever.js") to the helper function instead of just the filename, problem solved.
Thank you so much. i wasted so much time not knowing this.
This worked for me
function lazyLoad(fileName, isNamed) {
return lazy(() => {
const promise = import(`./${fileName}`);
if (isNamed) {
return promise.then(module => ({ default: module[fileName] }));
}
return promise;
});
}
Amazing video, thanks!!
Thanks for an other amazing video, it would be great if you also add link to in description to related blog on your website. thanks
Nice work! 👍🏼
This was really helpful
So useful! My react app was taking long minutes to be loaded it weights something around 700MB, and my computer is a little weak, i thought it could be this, cause, until now, i didn't even know this was possible.
Great content! 👏
Thats some real advanced knowledge
Incredible 👏
Another awesome video. Tks.
this video... golden!!!!!!
Great video. Thank you.
Thanks, Kyle. Instead of writing wait promise and more codes (because this is web dev simplified), it was better to use fast or slow 3G throttling from network tab.
Hi Kyle, TY for the content, very useful videos
I usually use Lazy loading and suspense, but something that I didn't fully understand from your video was: What is the difference between using the fallback prop in VS useTransition ?
Excellent, thanks
Thanks for sharing your knowledge ❤ Please make videos abour Angular alsoo... Please 😢
Huge love from India Kyle :) ❤️
Great tutorial
You forgot to add this is only suitable for really huge components. If you "lazyload" all the things you are actually slowing down your application at runtime to gain faster load at the start. This way your page/app will become laggy on slower connection speeds and this is not advised in production. It has terrible impact on look&feel. You want your apps to be responsive and snappy even if it loads 0.2s slower at the beginning, you will probably never reload this page (SPA) and most of the things will get cached.
I have changed many files from named export to default export in order to apply lazy loading. Then, I found a lib react-lazily which help me do the job. Anyways, thank for sharing the lazyLoading function. cool!
Kyle you have a problem your audio output on your videos. Use +0db or not use lower then -2db and alsoe there is audio balancer tools on video editing tools if you worried about audio changes. I just have to turn up the volume almost all the way for your videos and I can't turn anything else on, because any other audio output, video music etc. it's terribly loud.
Excellent!
Very helpful
By the way, you can also simulate slow internet using your chrome browser by setting the network speed in the developer tools.
You are awesome. Can you make a small code for login and register pages using fetch, that shows conditional component after login/before login? if you have already made such a video, can you provide a link?
excellent stuff
considering its pros, should we always use it? there wasn’t much discussion about its disadvantages so i’m not sure if it’s bad to always split code like that
Thanks a million
Very great video
useful. thanks
Thanks from Kerala
Wow...
Thanks a bunch. This will help a lot.
There's a project that I'm currently working on; after building it up... One of the main js files is about 24mb... How can I optimise it more... It takes a lot of data and time to load from the web server.
Great. I use the lazy Suspense in my router too.
But what about error baoundary? How and where to use it?
appreciation from the Philippines 🇵🇭 we’re learning a lot
They are great strategy for specific need, however if u required to do so much of the code splitting on so many components, u might as well go for micro front-end, solve it entirely instead of pieces here and there
Thank you
What's the best way to manage having a significant number of elements? I'm building a react application for myself to do engine ecm editing. The binary is 3.4mb, the json for the parameters is 8mb and there are 17,600 parameters. About 2000 of those are x, xy and xyz tables. Total rendered component count is probably north of 25,000.
the way you explain >>>>
The best!
Could you make some videos about node.js eventemmiters, the resources for them have always sucked
very very useful
you can also throttle your network from the chrome dev tools
great video,
Thanks!
You're welcome!
Code Splitting is Splitting bundle into multiple parts that can be downloaded over time ('lazy loading") . That help us to easy optomize our application , fix real performance issues...
Hey everyone! I found that when you use the `lazyLoad()` function that Kyle created, vite cannot analyze the dynamic path for the import and therefore will not be able to properly build the js and file paths for these components when you run the build command.
To get around this I found that you can pass the whole import function into the custom function like this `lazyLoad(import('./components/AdminData.jsx'), 'AdminData')` and use that instead of assigning the promise variable. This keeps the import path static so vite can work with it during build time.
`export const lazyLoad = (importCall, namedExport) => {
return lazy(() => {
if (namedExport == null) return importCall;
return importCall.then(module => ({ default: module[namedExport] }));
});
}`
it worked, but with some bugs. For instance, i've tried to put it in a route to reset password, the page wasn't loaded as i playned, but since i click the email link do be redirect to the reset page, the page was rendering, but in the source from dev tools, this page wasn't downloaded. Although the page have showed to me hahahaha
When it comes to React Router and react router loader and action. Code splitting does not work in remix way , however we have to write action and loader into its own file. I see Next React router update will have this feature update.
Love Suspense, found out about it from @PedroTech’s channel. This is nice to do at a component level when you want parts or the page to be interactive prior to loading an item
Amazing
Have you ever tried webpack's module federation plugin ?
That's why we Use Nextjs For production ready app.
great video
Thats basically a Resumable Hydration (Up to 4:25), that is what Qwik is doing under the hood
A nice method I use for simulating a slow connection is to run my React server out of a docker container, but use an Nginx container to proxy there configured to slow down the connection
You can also use the network speed in the browser development tools to slow down network requests
Firefox gives a lot of presets for different speeds
Hi. Can we dynamic import npm package like axios and moments?
Dynamic import would it affect the server side rendering for SEO?
Ie. Dynamic import head meta component at next js, incremental server side rendering?
Hope can get your reply.
And that for the video, it really simplify many concept
you can do incremental rendering ruclips.net/video/o3JWb04DRIs/видео.html
very useful
I love you thanks