IMPLEMENTING LAZY LOADING IN REACT
Introduction:
I OLEABHIELE DANIEL DONALD a mid-level Frontend Developer will be introducing you to this wonderful feature called Lazy loading today,Lazy loading is a technique in web development that enables the loading of assets or components only when they are needed, improving the overall performance of a web application. In React, the Suspense API is a powerful tool for handling asynchronous operations, making it easier to implement lazy loading seamlessly. In this article, we'll guide you through building a practical mini project that incorporates lazy loading using React's Suspense API.
Goal
Build a simple app where user can navigate to lazy loaded component as shown below:
Lazy loading explanation
Explaination for beginners
Imagine you have a magic toy box with lots of toys inside. Normally, when you want to play with a toy, you open the box and take it out. Now, think of Suspense as a friendly helper who can quickly get the exact toy you want without you having to open the box all the time. It's like magic because it brings the toy to you only when you're ready to play with it!
Technically:
The Suspense API in React is like a smart assistant that helps handle waiting times for things to load in a web page. When we talk about "lazy," it means we only fetch or load things (like components or data) when we actually need them, not all at once. React.lazy is a tool that allows us to load parts of our app only when they're required, making our app faster and more efficient. Suspense then manages the waiting period and shows a backup content (fallback) to keep the user engaged while waiting for the main content to arrive. This combination of lazy loading and Suspense makes our web apps feel faster and more responsive.
Now let’s get back to building our app:
Prerequisites:
Before diving into the implementation, ensure you have the following:
Basic understanding of React and JSX. Node.js and npm installed on your machine
Implementation:
npx create-react-app lazy-loading-project
cd lazy-loading-project
2. Install React Router: Install React Router to manage navigation within your app. Also install bootstrap
Recommended by LinkedIn
npm install react-router-dom bootstrap
3. Create Components
Design a few components for your mini project. For example, a home page, about page, and a dynamically loaded component.
Create components/Home.js in src folder:
import React from "react";
import { useNavigate } from "react-router-dom";
const Home = () => {
let navigate = useNavigate();
function goToLazyComponent() {
navigate("/lazy");
}
return (
<div>
<p>Home Page</p>
<button className="btn btn-primary" onClick={() => goToLazyComponent()}>
Go to lazy
</button>
</div>
);
};
export default Home;
Create components/About.js:
// About.js
import React from 'react';
const About = () => {
return <div>About Page</div>;
};
export default About;
Create components/LazyLoadedComponent.js:
// LazyLoadedComponent.js
import React from "react";
const LazyLoadedComponent = () => {
// Simulate a delay for lazy loading
const fetchData = () => new Promise((resolve) => setTimeout(resolve, 10000));
return (
<div>
<p>This component is lazily loaded!</p>
</div>
);
};
export default LazyLoadedComponent
Here we are using promise with setTimeOut to simulate delay in loading page.
4. Set up Routing
Configure routing using React Router in your App.js file.
// App.js
import React, { lazy, Suspense } from "react";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import Home from "./components/Home";
import About from "./components/About";
import "bootstrap/dist/css/bootstrap.min.css";
const LazyLoadedComponent = lazy(() =>
import("./components/LazyLoadedComponent")
);
const App = () => {
return (
<Router>
<Routes>
<Route path="/" exact element={<Home />} />
<Route path="/about" element={<About />} />
<Route
path="/lazy"
element={
<Suspense fallback={<div>Loading...</div>}>
<LazyLoadedComponent />
</Suspense>
}
/>
</Routes>
</Router>
);
};
export default App;
Explanation about how Suspense allows fallback loading state:
The Suspense component in React allows you to specify a fallback content to be displayed while waiting for the lazy-loaded component to resolve. In our example, the fallback prop inside Suspense is a simple loading message, but it could be a loader or any content you want to display during the loading period.
When the user navigates to the lazy-loaded route, React will automatically suspend rendering until the lazy component is fully loaded. The fallback content is then shown until the lazy component is ready to be displayed. This creates a smooth user experience and eliminates the need for additional loading state management.
Conclusion:
In this mini project, we explored the implementation of lazy loading in a React application using the Suspense API. By leveraging React.lazy and Suspense, we can dynamically load components, enhancing the performance of our application by only fetching what is necessary.
Full Stack Developer | Problem Solver | Expert in Efficient and Secure Software Development for Startups.
1yThis is a good project for beginners to learn about react. Keep up the good work 👍