Lazy Loading in React JS

React JS

Today we will explain how to implement Lazy Loading in React JS. In previous article we have explained how to fetch data from an API in React JS.

Basically lazy loading is the wait for something before render the component in React JS. Whenever we have to fetch data from an API then delay the response from the API then we set loader to load data. So that purpose react introduce lazy loading to display loader before the render component.

Syntax

syntax lazy loading in React js

Now we will implement lazy loading like as below example. First of all we will create a simple component using hello world message.

LazyLoading.js

import React, {Component} from 'react';

class LazyLoading extends Component {
    render() {
        return (
            <div>
                <h3>Hello World!</h3>
            </div>
        );
    }
}

export default LazyLoading;

Now we will import lazyloading component in the App.js using lazy like as below code example.

App.js

import React, {lazy, Suspense} from 'react';
import './App.css';
const LazyLoading = lazy(
    () =>
        new Promise((resolve, reject) =>
            setTimeout(() => resolve(import("./components/LazyLoading/lazyLoading")), 2000)
        )
)

function App() {
  return (
    <div className="App">
        <h2>Lazy Loading in React JS</h2>
        <Suspense fallback={<div>Please wait...</div>}>
            <LazyLoading />
        </Suspense>
    </div>
  );
}

export default App;

Output

lazy loading in react js

In the above code we have used lazy and suspense to implement lazy loading. We have import lazyloading.js file in the lazy function. In the lazy function we have used setTimeout with promise to delay the response after 2 seconds. After 2 seconds lazyloading component will render. We have used suspense with fallback to display the loading message before render the lazyloading component. In the suspense we can set any message or spinner using fallback.

We can implement lazy loading when we fetch the data from an API because sometimes API gives response after some time. Before lazy loading we have used state to display loader before the render component but right now we can use lazy loading to display loading message or spinner before render the component.

Conclusion

So in this article we have explained about how to implement lazy loading in React JS. Using this tutorial anyone can easily understand lazy loading in React JS.

If you want to improve this tutorial or find anything wrong/incorrect then please leave a message using below comment box.

Leave a Reply

Your email address will not be published. Required fields are marked *

4 × 1 =