What is Lazy Loading?
For a frontend developer, It's very important to know the different ways to optimize the performance to improve the user experience. Lazy loading is one the most common optimization technique for any mobile or web application. We use the concept of lazy loading to decrease the DOM load time and to increase the speed of the application. Now all the popular app we see like Facebook, Twitter, Instagram uses lazy loading to fetch the data on demand. In the lazy loading, all the data are not fetched at once instead chunks of data are provided to the user at one go. This way mobile/web application is optimized very easily and most of the platforms uses today to increase the user experience.
Advantages of Using Lazy Loading
- Implementation of lazy loading in ReactJS is very easy.
- Unwanted code execution can be avoided.
- Minimum usage of time and memory makes it a cost-effective approach and improves the user experience.
Disadvantages of Using Lazy Loading
- It may affect the website ranking on search engines.
- Extra line of code is added.
In this article, we will see how to lazily load the pages of the ReactJS application to make it more optimized.
Syntax
const UserListComponent = React.lazy(() => import('./UserListComponent'));
Example
In the below example, We will see how can we easily implement lazy loading for a component in the ReactJS application
By default, we have a component App, and now we will create a new component(UserList) which will be lazily loaded when the user navigates to a specific route.
UserList.js Component
import React from 'react';
const UserList = () =>{
return(
<div style={{textAlign:'center'}}>
<h1>User Listing Component</h1>
</div>
)
}
export default UserList;
Now we will see the code inside App.js file which is having the lazy loaded component code inside it.
import React, { Suspense, lazy } from 'react';
import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom';
const UserList = lazy(() => import('./UserList'));
const App = () => (
<Router>
<Suspense fallback={<div style={{textAlign:'center'}}>Loading...</div>}>
<Switch>
<Route path="/user-list" component={UserList} />
<Route
path="/"
exact
render={() => (
<div style={{textAlign:'center'}}>
<h1 >Home Page</h1>
<Link to="/user-list">User List</Link>
</div>
)}
/>
</Switch>
</Suspense>
</Router>
);
export default App;
Now when the app runs using npm start command then it looks like below:
Here when the ReactJS app loads the first time then only the App.js component loads and the home page renders over the browser and UserList loads only when the user navigates to the user-list route this way app loads faster and it makes a big difference when we work with complex applications in Reactjs.
Thanks!