When should you use React's lazy loading feature?
P粉976737101
2023-08-24 23:11:02
<p>I have a fairly large application and the bundle size is now about 2MB (about 3 chunks). To improve load times, I decided to start using the relatively new React Lazy. </p>
<p>This is an example of lazy loading: </p>
<pre class="brush:php;toolbar:false;">const Wizard = React.lazy(() => import('./components/wizards/Wizard'));</pre>
<p>I understand the general idea of the concept, but I'm still having a hard time understanding what the downside is other than occasionally having to wait a while for chunks to load. </p>
<p>Based on what I've read, I have no reason to use regular imports. </p>
<p><strong>My question is: Should I use lazy loading on every component import in my application? Why? why not? </strong></p>
<p>I'd love to hear your thoughts. </p>
I haven't started using it yet. But I think the most optimistic approach is to do regular imports of all the components you need on the homepage. Any other routes that are not the homepage should use lazy loading. This is the general train of thought I have.
No, not required for every component. It only makes sense to use it in every layout or page. A good place to start is routing. Most people on the web are used to page transitions taking a certain amount of time to load. You also tend to re-render the entire page at once, so your users are less likely to interact with other elements on the page at the same time.
For example, you are creating a news aggregation application. Your application consists of two pages such as
NewsList
andNewsItemPage
. Each page contains several different components. In this example, it makes sense to use lazy loading components for every other page. It will then load the components it needs.The application also has a
Header
andFooter
. They should be loaded in the usual way. Because they are used on every page and loading asynchronously doesn't make sense.