
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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="/https/www.tutorialspoint.com/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.
Advertisements