Steps to Implement Lazy Loading
- Recognize the component you want to Lazy Load. These are mostly Large or complex which is not necessary for all the users when the page loads.
- Import the `lazy()` and Suspense components from the React package
- Use the `lazy()` function to dynamically import the component you want to lazy load:
Note that the argument to the `lazy()` function should be a function that returns the result of the import() function. - Wrap the lazy-loaded component in a `Suspense` component, which will display a fallback UI while the component is being loaded:
<Suspense fallback={<div>Loading...</div>}>
<MyComponent />
</Suspense>
Example: This example uses the Suspense component and lazy method to implement the lazyloading for specific components.
Javascript
import React from "react" ; import { Suspense, lazy } from "react" ; const Component1 = lazy(() => import( '../src/LazyContent/myComponent1' )) const Component2 = lazy(() => import( '../src/LazyContent/myComponent2' )) function App() { return ( <> <h1> Lazy Load</h1> <Suspense fallback= {<div>Component1 are loading please wait...</div>}> <Component1 /> </Suspense> <Suspense fallback= {<div>Component2 are loading please wait...</div>}> <Component2 /> </Suspense> </> ); } export default App; |
Output:
Lazy Loading in React and How to Implement it ?
Lazy Loading in React JS helps to optimize the performance of React applications. The data is only rendered when visited or scrolled it can be images, scripts, etc. Lazy loading helps to load the web page quickly and presents the limited content to the user that is needed for the interaction lazy loading can be more helpful in applications that have high-resolution images or data that alters the loading time of the application.
Table of Content
- Lazy Loading in React
- Steps to Implement Lazy Loading
- Advantages of using Lazy loading in react applications
- Conclusion