Skip to content

Commit

Permalink
Lazy Loading
Browse files Browse the repository at this point in the history
  • Loading branch information
sunilsoni committed Oct 17, 2023
1 parent 2bce71b commit c33ecb6
Showing 1 changed file with 101 additions and 0 deletions.
101 changes: 101 additions & 0 deletions docs/ui/react/components.md
Original file line number Diff line number Diff line change
Expand Up @@ -1716,7 +1716,108 @@ function getDisplayName(WrappedComponent) {
## Lazy Loading
### Set up lazy loading components
**1. REACT.LAZY():**
**React.lazy** is a function that lets you load components lazily through what is called code splitting without help from any external libraries. It makes possible for us to dynamically import components but they are rendered like regular components. This means that the bundle containing the component will only be loaded when the component is rendered.
React.lazy() takes a function that returns a promise as it\'s argument, the function returns a promise by calling import() to load the content. The returned Promise resolves to a module with a default containing the React Component.
```js
// Without Lazy
import MyComponent from './MyComponent';

// With Lazy
const MyComponent = React.lazy(() => import('./MyComponent'));
```
**2. SUSPENSE:**
**React.Suspense** is a component that can be used to wrap lazy components. A React.Suspense takes a fallback prop that can be any react element, it renders this prop as a placeholder to deliver a smooth experience and also give user feedback while the lazy component is being loaded.
```js
/**
* Suspense
*/
import React, { Suspense } from 'react';

const MyComponent = React.lazy(() => import('./MyComponent'));

const App = () => {
return (
<div>
<Suspense fallback={<div>Loading ... </div>}>
<MyComponent />
</Suspense>
</div>
);
}
```
**Example:**
```js
/**
* React Lazy Loading Routes
*/
import React, { Suspense, lazy } from "react";
import { Switch, BrowserRouter as Router, Route, Link } from "react-router-dom";

const Home = lazy(() => import("./Home"));
const ContactUs = lazy(() => import("./ContactUs"));
const HelpPage = lazy(() => import("./Help"));

export default function App() {
return (
<Router>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/contact-us">ContactUs</Link></li>
<li><Link to="/help">HelpPage</Link></li>
</ul>
<hr />
<Suspense fallback={<h1>Loading...</h1>}>
<Switch>
<Route exact component={Home} path="/" />
<Route component={ContactUs} path="/contact-us" />
<Route component={HelpPage} path="/help" />
</Switch>
</Suspense>
</Router>
);
}
```
---
## ZZZZZ
---
## ZZZZZ
---
## ZZZZZ
---
## ZZZZZ
---

0 comments on commit c33ecb6

Please sign in to comment.