- ReactJS Tutorial
- ReactJS - Home
- ReactJS - Introduction
- ReactJS - Installation
- ReactJS - Features
- ReactJS - Advantages & Disadvantages
- ReactJS - Architecture
- ReactJS - Creating a React Application
- ReactJS - JSX
- ReactJS - Components
- ReactJS - Nested Components
- ReactJS - Using Newly Created Components
- ReactJS - Component Collection
- ReactJS - Styling
- ReactJS - Properties (props)
- ReactJS - Creating Components using Properties
- ReactJS - props Validation
- ReactJS - Constructor
- ReactJS - Component Life Cycle
- ReactJS - Event management
- ReactJS - Creating an Event−Aware Component
- ReactJS - Introduce Events in Expense Manager APP
- ReactJS - State Management
- ReactJS - State Management API
- ReactJS - Stateless Component
- ReactJS - State Management Using React Hooks
- ReactJS - Component Life Cycle Using React Hooks
- ReactJS - Layout Component
- ReactJS - Pagination
- ReactJS - Material UI
- ReactJS - Http client programming
- ReactJS - Form Programming
- ReactJS - Controlled Component
- ReactJS - Uncontrolled Component
- ReactJS - Formik
- ReactJS - Conditional Rendering
- ReactJS - Lists
- ReactJS - Keys
- ReactJS - Routing
- ReactJS - Redux
- ReactJS - Animation
- ReactJS - Bootstrap
- ReactJS - Map
- ReactJS - Table
- ReactJS - Managing State Using Flux
- ReactJS - Testing
- ReactJS - CLI Commands
- ReactJS - Building and Deployment
- ReactJS - Example
- Hooks
- ReactJS - Introduction to Hooks
- ReactJS - Using useState
- ReactJS - Using useEffect
- ReactJS - Using useContext
- ReactJS - Using useRef
- ReactJS - Using useReducer
- ReactJS - Using useCallback
- ReactJS - Using useMemo
- ReactJS - Custom Hooks
- ReactJS Advanced
- ReactJS - Accessibility
- ReactJS - Code Splitting
- ReactJS - Context
- ReactJS - Error Boundaries
- ReactJS - Forwarding Refs
- ReactJS - Fragments
- ReactJS - Higher Order Components
- ReactJS - Integrating With Other Libraries
- ReactJS - Optimizing Performance
- ReactJS - Profiler API
- ReactJS - Portals
- ReactJS - React Without ES6 ECMAScript
- ReactJS - React Without JSX
- ReactJS - Reconciliation
- ReactJS - Refs and the DOM
- ReactJS - Render Props
- ReactJS - Static Type Checking
- ReactJS - Strict Mode
- ReactJS - Web Components
- Additional Concepts
- ReactJS - Date Picker
- ReactJS - Helmet
- ReactJS - Inline Style
- ReactJS - PropTypes
- ReactJS - BrowserRouter
- ReactJS - DOM
- ReactJS - Carousel
- ReactJS - Icons
- ReactJS - Form Components
- ReactJS - Reference API
- ReactJS Useful Resources
- ReactJS - Quick Guide
- ReactJS - Useful Resources
- ReactJS - Discussion
ReactJS - lazy()
Lazy loading is a React method that allows us to delay loading a component's code until it is required. Lazy loading allows us to load specific pieces of our code just when they are ready to use, rather than loading everything when our program starts.
Syntax
import { lazy } from 'react'; const MyComponent = lazy(load)
Parameters
load − It is a function which returns a Promise. React will only call this function the first time we try to render the component.
Return Value
The lazy function returns a React component for use in our program. Attempting to render the code while it is still loading will lead it to suspend, and we can use <Suspense> to display a loading message.
Examples
Example 1
Now we are going to create a complete application with lazy loading that needs multiple files and configurations. It is a simple example of a React project that makes use of lazy loading for components. So we will create 2 components called ComponentA and ComponentB. And then we will call these components in the main component called App.
ComponentA.js
import React from 'react'; const ComponentA = () => { return <div>This is Component A</div>; }; export default ComponentA;
ComponentB.js
import React from 'react'; const ComponentB = () => { return <div>This is Component B</div>; }; export default ComponentB;
App.js
import React, { lazy, Suspense } from 'react'; const ComponentA = lazy(() => import('./ComponentA')); const ComponentB = lazy(() => import('./ComponentB')); const App = () => { return ( <div> <h1>Lazy Loading App</h1> <Suspense fallback={<div>Loading...</div>}> <ComponentA /> <ComponentB /> </Suspense> </div> ); }; export default App;
Output
In the browser, navigate to http://localhost:3000 and we should see our lazy-loaded components.
This is a simple example, lazy loading is frequently used for larger components or routes for better performance. Also, for more complex lazy loading in a multi-page application, consider leveraging technologies like React Router.
Example 2
Let us create a basic React app that renders a dynamic list of things with a lazy loading method. We will have a main component (ItemList) and individual item components that will be loaded concurrently.
// src/ItemList.js import React, { lazy, Suspense } from 'react'; import Loading from './Loading'; // Lazy load Item component const Item = lazy(() => delayForDemo(import('./Item'))); const itemsData = [ { id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }, { id: 3, name: 'Item 3' }, ]; const ItemList = () => { return ( <div> <h2>Item List</h2> <Suspense fallback={<Loading />}> {itemsData.map((item) => ( <Item key={item.id} name={item.name} /> ))} </Suspense> </div> ); }; export default ItemList; // Add a fixed delay function delayForDemo(promise) { return new Promise(resolve => { setTimeout(resolve, 2000); }).then(() => promise); }
Loading.js
export default function Loading() { return <p><i>Loading...</i></p>; }
src/App.js
import React from 'react'; import ItemList from './ItemList'; function App() { return ( <div> <h1>Lazy Loading Example</h1> <ItemList /> </div> ); } export default App;
Output
In the browser, navigate to http://localhost:3000 and we should see our lazy-loaded list of items.
This example shows how to use lazy loading to improve our app's initial loading performance, especially when working with huge lists of components.
Example 3
Let us create another example where we will use the lazy method to load a component which contains an image.
LazyComponent.js
import React from 'react'; const LazyComponent = () => { return ( <div> <p>This component contains a image:</p> <img src="https://via.placeholder.com/300" alt="Lazy Loaded Image" /> </div> ); }; export default LazyComponent;
Loading.js
export default function Loading() { return <p><i>Loading...</i></p>; }
App.js
import React, { lazy, Suspense } from 'react'; import './App.css' // Lazy load the component const LazyComponent = lazy(() => delayForDemo(import('./LazyComponent'))); const App = () => { return ( <div className='App'> <h1>Lazy Loading Example</h1> <p>This is the main component.</p> {/* Suspense to handle the lazy loading */} <Suspense fallback={<div>Loading...</div>}> <LazyComponent /> </Suspense> </div> ); }; export default App; // Add a fixed delay function delayForDemo(promise) { return new Promise(resolve => { setTimeout(resolve, 2000); }).then(() => promise); }
Output
In this example, the LazyComponent component contains an image loaded from a source. We use the lazy method to load this component in the App component.
As before, the Suspense component handles the asynchronous loading of the lazy component and displays a fallback UI (in this case, a simple "Loading..." message) while the component is being loaded.
Summary
Lazy loading in React improves performance by loading only the code that is required, making our app faster and more efficient. We have created two simple applications using a lazy loading method. These are very simple examples, lazy loading is frequently used for larger components or routes to increase performance.
To Continue Learning Please Login
Login with Google