1. 程式人生 > >Lazy loading (and preloading) components in React 16.6

Lazy loading (and preloading) components in React 16.6

Now, the user will only see the “Loading…” fallback if they click a stock in less than 1 second after the table is displayed. Try it.

You could also enhance the lazy function to make it easier to preload components whenever you need:

Prerendering a component

For our small demo app that’s all we need. For bigger apps the lazy component may have other lazy code or data to load before it can be rendered. So the user would still have to wait for those.

Another approach for preloading the component is to actually render it before we need it. We want to render it but we don’t want to show it, so we render it hidden:

Diff

React will start loading <StockChart/> the first time the app is rendered, but this time it will actually try to render <StockChart/>

so if any other dependency (code or data) needs to be loaded it will be loaded.

We wrapped the lazy component inside a hidden div so it doesn’t show anything after it is loaded. And we wrapped that div inside another <React.Suspense/> with a null fallback so it doesn’t show anything while it’s being loaded.

Note: hidden is the HTML attribute for indicating that the element is not yet relevant. The browser won’t render elements with this attribute. React doesn’t do anything special with that attribute(but it may start giving hidden elements a lower priority in future releases).

What’s missing?

This last approach is useful in many cases but it has some problems.

First, the hidden attribute for hidding the rendered lazy component isn’t bulletproof. For example, the lazy component could use a portal which won’t be hidden (there is a hack that doesn’t require an extra div and also work with portals, but it’s a hack, it will break).

Second, even if the component is hidden we are still adding unused nodes to the DOM, and that could become a performance problem.

A better aproach would be to tell react to render the lazy component but without comitting it to the DOM after it’s loaded. But, as far as I know, it isn’t possible with the current version of React.

Another improvement we could do is to reuse the elements we are rendering when preloading the chart component, so when we want to actually display the chart React doesn’t need to create them again. If we know what stock the user will click we could even render it with the correct data before the user click it (like this).

That’s all. Thanks for reading.

For more stuff like this follow @pomber on twitter.