Lazy loading is not a new concept.
It has existed for quite some time.
The term “lazy loading” refers to the requirement for a component or piece of code to be loaded only when it is required.
Data fetching and code splitting are other terms for the same thing.
When it comes to React, it bundles and delivers all of the code at the same time. This isn’t a bad idea in most cases because React SPAs (single page apps) are short and have little performance impact.
What if we have a big app, like a content management system with a customer portal, an admin portal, and so on? In this case, it does not appear that loading the complete application is a wise idea.
When we know that certain code/features will not be accessible to all users or will not be used frequently by the user, we should load them when the user requests them. This improves the user experience as well as the loading time.
Syntax
const Component = React.lazy(() => import('./Component'));
Example
import React, { Suspense, lazy } from 'react'; import { BrowserRouter as Router, Route, Switch } from 'react -router-dom'; const Home = lazy(() => import('./Home')); const App = () => ( <Router> <Suspense fallback={<div>Loading...</div>}> <Switch> <Route path="/home" component={Home} /> <Route path="/" exact render={() => ( <div> <h1>Home page</h1> <a href="/about">Click here</a> </div> )} /> </Switch> </Suspense> </Router> ); export default App;