Wednesday, May 6, 2020

React.lazy with Suspense example

In the previous post we saw that 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.

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: