Suspense in ReactJS



In this article, we will learn how to show a loader while the component is being lazily loaded.

When the components are lazily loaded, it requires a fallback to be shown to indicate that the component is being loaded in the DOM.

Syntax

<Suspense>

Example

In this example, we will build a Routing application that lazily loads the component and displays a loader while the component is being loaded lazily.

App.jsx

import React, { Suspense, lazy } from 'react'; import { BrowserRouter as Router, Route } from 'react-router-dom'; import Loader from './Loader.js'; const Contact = lazy(() => import('./Contact')); const App = () => (    <Router>    <Suspense fallback={<Loader />}>    <Route exact path="/contact" component={Contact} />    <Route       path="/"       exact       render={() => (          <div>             <h1>TutorialsPoint</h1>             <a href="/contact">Contact Us</a>          </div>       )}    />    </Suspense>    </Router> ); export default App;

Contact.js

import React from 'react'; const Contact = () => {    return (       <div>          <h1>Contact Us</h1>          <h4>You already know us</h4>       </div>    ); }; export default Contact;

Loader.js

import React from 'react'; const Loader = () => {    return <div>Please wait...</div>; }; export default Loader;

In the above example, when the component is being lazily loaded, the Loader component is loaded in the DOM as a fallback to this component.

Output

This will produce the following result.

Updated on: 2021-03-19T11:15:05+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements