The original:Blog. Bitsrc. IO/lazy – loadin…

While the hooks that finally made it out in React 16.8.1 were notable, last year’s 16.6.0 release also included an attractive new feature that made it easier to handle lazy loading without relying on third-party libraries.

Let’s see how you can use this feature to improve application performance and build a better user experience.

As a rule of thumb, when building components, it is useful to generalize them with bit-like tools — you can share your components and use them in any application to speed up development and keep DRY.

What is react.lazy ()?

This new feature makes it possible to lazily load the React component through code Splitting without any additional libraries. Lazy loading is a technique where necessary or important user interface items are rendered first, while less important items are quietly loaded. The technology is fully integrated into react’s own core library. We used to use react-loadable for this purpose, but now use react.lazy().

Suspense suspends components

Suspense is a component required for delay functions and is usually used to wrap lazy-loaded components. Multiple lazy-loaded components can be packaged in a suspense component. It also provides a fallback property that is used to explicitly specify some react elements during lazy loading of components.

Why are delays and hangs important?

First, the packaging tool summarizes all code components sequentially into a javascript block that is passed to the browser. But as the app grew, we noticed that the size of the package grew. This can lead to applications that are slow to load and difficult to use. With code splitting, code packages can be divided into smaller chunks, with the most important being loaded first and the rest of the less important being loaded lazily.

At the same time, we know that one of the best practices in building applications is to take into account users’ use of mobile Internet data and other slow Internet connections. As a developer, you should be able to control the user experience even during the hang phase when resources are read into the DOM.

start

According to react documentation, you already have a WebPack configuration if you use the following techniques:

  • CRA (create react app)
  • Next js
  • Gatsby

If not, you need to set up your own packaging. For example, read Installation and Getting Started in the official Webpack documentation.

Demo

Create a React app with create-React-app and implement a suspended lazy load in it. It will display the names and number of albums by the top artists of 2019 on MTV Base. I created a clean application with create-react-app and included a simple component that we could use in this example.

  • Cloning gitlab.com/viclotana/r…
  • Unzip the file and open a terminal window
  • Install the node modules dependencies for your project in the root directory of the unzipped file
  • Start the development server with the following command:
$ sudo npm start
Copy the code

It’s a simple app, and the artist’s data is read from a store in the app. Of course, you can also write this code yourself, the application SRC should have these files:

  1. Artists.js
import React from'the react;import'. / App. CSS ';import artists from". / store ";export default function Artists(){
 return (
   <>
   <h1>MTV Base Headline Artists 2019</h1>
   {artists.map(artist =>(
   <div id=Card - "body" key={artist.id}>
    <div className="Card">
     <h2>{artist.name}</h2>
     <p>genre: {artist.genre}</p>
     <p>Albums released: {artist.albums}</p>
    </div>
   </div>
    ))}
   </>
);
}
Copy the code
  1. Store.js
export default[{id:"1",name: “Davido”,
  country"They were,genre: "Afro - Pop."albums:"2"}, {id:"2",name: “AKA”,
  country"South Africa",genre: “Hip-Hop”,
  albums:"4"}, {id:"3",name: “Seyi Shay”,
  country"They were,genre: “R&B”,
  albums:"2"}, {id:"4",name: "Sauti Sol,"country: “Kenya”,
  genre: “Soul”,
  albums:"3"});Copy the code
  1. Index.js
import React from'the react;import ReactDOM from'the react - dom;import'. / index. The CSS ';import Artists from'. / Artists';class App extends React.Component {
 render(){
  return(
   <div className="App">
    <Artists />
   </div>
   );
 }
}
ReactDOM.render(<App />, document. GetElementById (" root "));Copy the code
  1. App.css
.App {
 text-align: center;
}
h1 {
 padding: 30px;
}
#card-body {
 display: inline-flex;
 padding: 10px;
 margin: 30px 30px;
 border: 5px solid rgb(93, 171, 207);
 border-radius: 8px;
 background: lightblue;
}
Copy the code

Now let’s look at how to handle lazy loading of artist components with react.lazy and suspense.

  • inindex.jsSuspense for lazy and suspense in React
import { Suspense, lazy } from 'react';
Copy the code
  • To render a dynamically imported component like a regular component, use the react. Lazy function syntax provided in the React documentation, as follows:
const OtherComponent = React.lazy((a)= > import('./OtherComponent'));

function MyComponent() {
  return (
    <div>
      <OtherComponent />
    </div>
  );
}
Copy the code
  • Applied to our artist component:
const Artists = React.lazy((a)= > import('./Artists'));

function MyComponent() {
  return (
    <div>
      <Artists />
    </div>
  );
}
Copy the code

If the module containing the artist component does not finish loading during App component rendering, it must display fallback content that indicates waiting — for example, a load indicator. Here is the syntax for using Suspense components to do this:

const OtherComponent = React.lazy((a)= > import('./OtherComponent'));

function MyComponent() {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>} ><OtherComponent />
      </Suspense>
    </div>
  );
}
Copy the code

Apply to the artist component:

const Artists = React.lazy((a)= > import('./Artists'));

function MyComponent() {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>} ><Artists />
      </Suspense>
    </div>
  );
}
Copy the code

Put the above together, index.js looks like this:

import React, { lazy, Suspense } from'the react;import ReactDOM from'the react - dom;import'. / index. The CSS ';// import Artists from ‘./Artists’;
const Artists = lazy((a)= > import(". / Artists'))class App extends React.Component {
 render(){
  return(
   <div className="App">
    <Suspense fallback={<h1>Still Loading...</h1>} ><Artists />
    </Suspense>
   </div>
  );
 }
}
ReactDOM.render(<App />, document. GetElementById (" root "));Copy the code

It should run so fast on your localhost that you won’t even notice the change. But you can create statistical code for a period of time, or simulate slow networks:

  • Open dev Tools in your browser
  • Select the network TAB
  • Click the online TAB on the far right to display other options (down arrow on the far right)
  • Choose the fast 3 g

Now refresh your browser to see how lazy loading happens…

Multiple lazy-loaded components

So add a quick widget for rendering titles to see how react.lazy still uses only one suspense component:

Create performers.js file:

mport React from'the react;import'. / App. CSS ';export default function Performers(){
 return (
  <>
  <h2>These are the MTV Base Headline Artists...</h2>
  </>
 );
}
Copy the code

And add a line of lazy loading code to index.js:

import React, { lazy, Suspense } from'the react;import ReactDOM from'the react - dom;import'. / index. The CSS ';const Artists = lazy((a)= > import(". / Artists'))const Performers = lazy((a)= > import(". / Performers'))class App extends React.Component {
 render(){
  return(
   <div className="App">
    <Suspense fallback={<h1>Still Loading...</h1>} ><Artists />
     <Performers />
    </Suspense>
   </div>
  );
 }
}
ReactDOM.render(<App />, document. GetElementById (" root "));Copy the code

Now, after placeholder elements are rendered in Suspense, two lazy-loaded components are immediately displayed.

This is different from loading every lazy-loaded component of loadable.

⚠️ Important Note

React.lazy and Suspense are not yet available for server rendering. The Loadable component is still highly recommended if you want to use code splitting in server-rendered applications and is well explained in its documentation.

conclusion

We saw how to implement lazy loading with the lazy and Suspense components provided by React. The above example is rudimentary compared to the many possibilities this new feature opens up. You can use it flexibly in your own projects and have fun coding!






–End–






Search fewelife concern public number reprint please indicate the source