Saturday, March 7, 2020

Lazy Loading React Components (with react.lazy and suspense)

Our first step is to create an React application using below command:

npm init react-app react-lazy-loading-component

Navigate to project folder and type npm start to start project on browser.

Make sure you execute command npm run build to prepare build script which will be deployed on server

Route-based code splitting

You have to install react-router-dom using npm install --save react-router-dom to use this functionality.

Deciding where in your app to introduce code splitting can be a bit tricky. You want to make sure you choose places that will split bundles evenly, but won’t disrupt the user experience.

A good place to start is with routes. Most people on the web are used to page transitions taking some amount of time to load. You also tend to be re-rendering the entire page at once so your users are unlikely to be interacting with other elements on the page at the same time.
Sample App.js

import {BrowserRouter as Router, Route, Switch} from 'react-router-dom';
import React, {Suspense, lazy} from 'react';
import './App.css';

import Header from './Header';

const Home = lazy(() => import('./Home'));
const AnotherHome = lazy(() => import('./AnotherHome'));

function App() {
    return (
        <div>
            <Router>
                <Header/>
                <div className="container">
                    <Suspense fallback={<div>Loading...</div>}>
                        <Switch>
                            <Route exact path="/" component={Home}/>
                            <Route exact path="/another-home" component={AnotherHome}/>
                        </Switch>
                    </Suspense>
                </div>
            </Router>
        </div>
    );
}

export default App;
Actually use of Suspense and Lazy will load components chunk by chunk when they needed, and once a component loaded into browser will not load second time.
GitHub Link https://github.com/pritomkucse/react-lazy-loading-component
Live Example at codesandbox.io

https://codesandbox.io/s/lazy-loading-react-components-with-reactlazy-and-suspense-2hx75

Make sure you see console to ensure that suspense callback working as expected:


No comments:

Post a Comment