Lazy Loading Components in React
⚡️ Lazy Loading Components in React
✅ What is Lazy Loading?
Lazy loading means loading parts of your application only when they are needed, instead of loading everything up front. In React, this is often used to improve performance by loading components on demand.
๐ง Why Use Lazy Loading?
✅ Reduces the initial load time of your app
✅ Improves performance, especially for large apps
✅ Saves bandwidth by loading only what the user needs
๐ How to Lazy Load a Component in React
React provides a built-in function called React.lazy() for lazy loading.
๐ฆ Example
Suppose you have a component called Profile.js.
✅ Step 1: Use React.lazy()
javascript
Copy
Edit
import React, { Suspense } from 'react';
const Profile = React.lazy(() => import('./Profile'));
✅ Step 2: Wrap it in <Suspense>
javascript
Copy
Edit
function App() {
return (
<div>
<h1>Welcome!</h1>
<Suspense fallback={<div>Loading...</div>}>
<Profile />
</Suspense>
</div>
);
}
๐น The fallback prop is what the user sees while the component is loading (like a spinner or message).
๐ฏ Best Practices
✅ Use lazy loading for routes or large components.
❌ Don’t overuse it for small or frequently used components.
✅ Combine with code splitting (e.g., React Router) for maximum benefit.
๐ Lazy Loading with React Router (v6+)
javascript
Copy
Edit
import { lazy, Suspense } from 'react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
const Home = lazy(() => import('./pages/Home'));
const About = lazy(() => import('./pages/About'));
function App() {
return (
<BrowserRouter>
<Suspense fallback={<p>Loading page...</p>}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</Suspense>
</BrowserRouter>
);
}
๐งช Lazy Loading Tips
Tip Description
✅ Error Boundaries Use them to catch loading errors
๐ซ No SSR support React.lazy() doesn’t work with server-side rendering
๐ Preload if needed Use import().then() to preload components before they’re needed
Learn MERN Stack Course in Hyderabad
Read More
React State Management Best Practices
Building a File Upload API in MERN
Setting Up WebSockets with Node and Express
Visit Our Quality Thought Training in Hyderabad
Comments
Post a Comment