Lazy loading component routing using Suspense API & React.lazy| React v16.6 — Part 1

Narendra Singh Rathore
3 min readDec 27, 2019

React 16.6 added a <Suspense> component that lets you “wait” for some code to load and declaratively specify a loading state (like a spinner) while we’re waiting.

Suspense for Data Fetching is a new feature that lets you also use <Suspense> to declaratively “wait” for anything else, including data. This page focuses on the data fetching use case, but it can also wait for images, scripts, or other asynchronous work.

Implementation

We can create a <SuspenseContainer>, scenario we would cover by this implementation are below:

  1. Showing loader when component is lazy loading on routing
  2. Showing loader when image is loading

1. Showing loader when component is lazy loaded on routing.

Skeleton component from material-ui.com

Note: we are using Skelton from material-ui for showing loader when component is loading lazily on route.

a) Our SuspenseContainer component

import React, { Suspense } from “react”;import Skeleton from “@material-ui/lab/Skeleton”;/**
*
* @param props Take no props, just return skeleton while components load lazy
*/
function Loader(props: any) {
const width = “98vw”;
const widthHalf = “50vw”;
const height = “50px”;
return (
<div style={{ padding: 10 }}>
<Skeleton
style={{ backgroundColor: “#cacaca” }}
variant=”text”
width={width}
height={height}
>
</Skeleton>
<Skeleton variant=”text” width={width} height={height}></Skeleton>
<Skeleton variant=”text” width={widthHalf} height={height}>
</Skeleton>
</div>

);
}
/**
* It take react component as children and using suspense api to show fallback component
* for lazy loading component using React.lazy https://reactjs.org/docs/code-splitting.html
* @param props children i.e React Component
*/
export default function SuspenseContainer(props: any) {
return <Suspense fallback={<Loader />}>{props.children}</Suspense>;
}

b) Routing sample( Note: we are using react-router-dom for routing implementation )

We just need to wrap our components in SuspenseContainer and provide them as reference using React.lazy import

Note: React.lazy takes a function that must call a dynamic import(). This must return a Promise which resolves to a module with a default export containing a React component.

The lazy component should then be rendered inside a Suspense component, which allows us to show some fallback content (such as a loading indicator) while we’re waiting for the lazy component to load.

import React, { lazy } from "react";
import { BrowserRouter as Router } from "react-router-dom";
/*** Lazy loading routes*/const Login = lazy(() => import("../components/stateless/Login/Login"));<Router>
<Switch>
<Route key="something">
<SuspenseContainer>
<Login/>
</SuspenseContainer>
</Route>
</Switch>
</Router>

Screenshot

Login component

All code can be found in repository link below

Fork and star if liked.

Thanks ✌

--

--