Thursday, May 7, 2020

Lazy loading React components

Lazy loading is loading dependent modules / components dynamically, this is done to optimize the initial load time of larger React Applications which have multiple components and 3rd part library dependencies.

In React 16.6 lazy loading is enabled by using React.lazy function and the Suspense component. React.lazy is used to lazy load react components from the same or different bundle file and the Suspense component is used to display a fallback UI till the dependent component / bundle is loaded. Lazy loading and code-splitting works together to enable optimization of initial load time for large React Applications.

In this post we shall see a simple example which uses React.lazy to lazy load a Child Component and display Loading… text till the child component is loaded. The example has 2 components, the App component is the parent component which laze loads the ChildComponent.

ChildComponent.js
import React from 'react';
import './App.css';

class ChildComponent extends React.Component {
render() {
        return (
        <div className="App">
            <header className="App-header">
            <p>Hello from Child Component.</p>
            </header>
        </div>
        );
    };
};
export default ChildComponent;

App.js (Parent Component)
import React, {Suspense} from 'react';
const ChildComponent = React.lazy(() => import('./ChildComponent'));

class App extends React.Component {
  render() {
    return (
      <div className="App">
        <header className="App-header">
        <Suspense fallback={<div>Loading...</div>}>
          <ChildComponent/>
        </Suspense>         
        </header>
      </div>
    );
  };
}
export default App;

Build and run the Application and the output will be as follows. Notice that when the page loads the fallback UI text Loading… gets displayed for a very brief time. Since this is a simple example the fallback UI disappears very quickly, if the application is large and contains multiple bundles then the fallback UI text will be displayed for more time till the component is loaded.




Search Flipkart Products:
Flipkart.com

No comments: