More

    React Lazy: Here’s everything defiend about it

    What is React Lazy? 

    React lazy is a new function in react that allows you to load react components in a lazy manner through code-splitting, without receiving help from any additional external libraries. Lazy loading is the technique that involves the rendering of only needed or critical user interface items first, then silently unrolling the non-critical items later. 

    Currently, it is fully integrated into the core react library itself. We formerly used react-loadable to achieve this but now we have react.lazy() in react core. 

     When sometime last year, the team at react released version 16.6.0, it enabled a shiny new feature that allowed us to very easily handle lazy loading without the help of third-party libraries. 

     Suspense-

    Suspense is a component required by the lazy function which is basically used to wrap lazy components. Many lazy components can. Be wrapped together with the help of the suspense component. It takes a fallback property that accepts the react elements you want to render as the lazy component is being loaded. 

     

    Why is lazy loading and suspense important? 

    The first step in bundling involves aligning our code components in progression and putting them under one javascript chunk that is then passed on to the browser, but since our application is growing, we notice that the bundles get very cumbersome in size. This can very swiftly make your application very hard and especially slow. 

    With the help of code splitting, the bundle can be split to smaller chunks where the most important chunk can be loaded first and then every other secondary one is lazily loaded. 

     We also know that while building applications, that as a best practice, consideration should be made for users using mobile internet data and others with really slow internet connections. We developers should always be able to control the user experience even during a suspense period when the resources are being loaded to the DOM. 

     

    Getting Started with React Lazy: 

    According to the react official documentation, you have webpack bundling already configured for use out of the box if you use it. 

     

          CRA (create react app) 

          Next js

          Gatsby

    If you are not, you will need to setup bundling yourself. For example, see the Installation and Getting Started guides on the Webpack official documentation. 

     Demo- 

    We are going to learn to build a react application that displays names and the number of albums of headline artists for MTV Base in 2019 using the create-react-app starter tool and then implement lazy loading with suspense in it. In this tutorial, we have cleaned up a  create-react-app to something simpler and built a simple component which we will use in this tutorial. 

     

          Clone the repository below- 

    https://gitlab.com/viclotana/react-lazy-load

     

          Unzip the file and open a new terminal

          Install the project’s node modules in the root directory of the unzipped file with the following line of command:

     

    $ sudo npm install

     

          The next step would be to start the development server with this line of command- 

    $ sudo npm start

     

     

    Here is our sample application, if you have cloned the repository, you will see that the artists data is loaded from a store inside the application. 

     

    You can also create one yourself and make the changes given below, the src folder of your application should look exactly like this. 

    1)    Artists.js

    import React from ‘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>    

     

    ))}   </>

     

    );

     

    }

     

    2)    Store.js

    export default [

     

    {

     

    id: “1”, 

     

    name: “Davido”, 

     

    country: “Nigeria”, 

     

    genre: “Afro-Pop”,

     

    albums: “2”

     

    },

     

     

    id: “2”, 

     

    name: “AKA”, 

     

    country: “South-Africa”,

     

    genre: “Hip-Hop”,

     

    albums: “4”

     

    },

     

    {

     

    id: “3”,

     

      name: “Seyi Shay”,

     

      country: “Nigeria”,

     

    genre: “R&B”, 

     

    albums: “2”

     

    },

     

     

    id: “4”, 

     

    name: “Sauti Sol”, 

     

    country: “Kenya”, 

     

    genre: “Soul”, 

     

    albums: “3”

     

    }

     

    ];

     

    3)    Index.js

    import React from ‘react’;

     

    import ReactDOM from ‘react-dom’;

     

    import ‘./index.css’;

     

    import Artists from ‘./Artists’;

     

    class App extends React.Component {

     

    render(){ 

     

    return(  

     

    <div className=”App”>

     

    <Artists /> 

     

    </div>  

     

    );

     

    }

     

    }

     

    ReactDOM.render(<App />, document.getElementById(‘root’));

     

    4)    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;

     

    }

     

    Let us now further learn how to use react.lazy and suspense to handle lazy loading of the artists component. 

     

          Head to the index.js file and import lazy and suspense from react like this: 

    import { Suspense, lazy } from ‘react’;

     

          To render a dynamic import as a regular component, the react documentation gives the react.lazy function syntax like so: 

     

    const OtherComponent = React.lazy(() => import(‘./OtherComponent’));

     

    function MyComponent() {

    return (

    <div>

    <OtherComponent />

    </div>

    );

    }

          Trying it out with our Artists component, we would have something like this: 

     

    const Artists = React.lazy(() => import(‘./Artists’));

     

    function MyComponent() {

    return (

    <div>

    <Artists />

    </div>

    );

    }

     

    In case the module containing the Artists is not loaded yet, by the time the App component renders, we must show some fallback content while we wait for the loading to finish. This can be a loading indicator, brought in action by the suspense component. Below is the syntax for adding suspense component to react lazy. 

     

    const OtherComponent = React.lazy(() => import(‘./OtherComponent’));

     

    function MyComponent() {

      return (

        <div>

          <Suspense fallback={<div>Loading…</div>}>

            <OtherComponent />

          </Suspense>

        </div>

      );

    }

     

     

    Combined with our artist component, this becomes: 

     

    const Artists = React.lazy(() => import(‘./Artists’));

     

    function MyComponent() {

    return (

    <div>

    <Suspense fallback={<div>Loading…</div>}>

    <Artists />

    </Suspense>

    </div>

    );

    }

     

    Combining it all together, your index.js file should look somewhat like the code below: 

     

    import React, { lazy, Suspense } from ‘react’;

     

    import ReactDOM from ‘react-dom’;

     

    import ‘./index.css’;

     

    // import Artists from ‘./Artists’;

     

    const Artists = lazy(() => 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’));

     

     

    On your localhost, it should be really fast, and it might make spotting changes difficult. However, you can create a timer helper or just simulate a slower network that would be able to show you exactly how the change occur is milliseconds. 

     

    This can be done by: 

     

          Opening the dev tools on your browser

          Choosing the network tab

          Clicking on the online tab at the far right to reveal other options (presets). 

          Choosing fast 3G

     

     

    You can now refresh your browser and watch how lazy loading occurs. 

     

    Multiple Lazy Components- 

     

    This is a small component that we need to add in order to render a header and see how the react lazy function handles it with only one suspense component. 

     

    Create a performers.js file in your src folder and add the code given below: 

     

    import React from ‘react’;

     

    import ‘./App.css’;

     

    export default function Performers(){

     

    return ( 

     

    <> 

     

    <h2>These are the MTV Base Headline Artists…</h2> 

     

    </>

     

    );

    }

     

     

    Then add the lazy component line in the index.js file and it should now look like this: 

     

    import React, { lazy, Suspense } from ‘react’;

    import ReactDOM from ‘react-dom’;

    import ‘./index.css’;

    const Artists = lazy(() => import(‘./Artists’))

    const Performers = lazy(() => 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’));

     

    This should now show the two lazily loaded components at once after the placeholder element from suspense has been rendered. 

     

     

     

    Recent Articles

    React Fragment: Find out what we encountered.!

      React Fragment: Hello Devs, in my journey of learning react I came across some frontend conditions where I had to render multiple react components,...

    React Admin: Documentation | Features | Dahboard | Templates

      React Admin is a framework for the front-end development of data-driven applications. That is operating in a browser over the top of REST or...

    React Hooks

      A hook is a component that allows us to use the features of React and state without defining a class. This feature is added...

    React Animation: A definitive guide

    React Animations Add-ons The ReactTransitionGroup add-on is a lower-level Applications Program Interface (API) component for creating react animations. And the ReactCSSTransitionGroup, is a component used...

    Create React App: A Complete guide for Beginners

      Create React App is the modern way of building an official Single Page React Application. It sets up a comfortable environment for building react...

    Related Stories

    Leave A Reply

    Please enter your comment!
    Please enter your name here