Lazy Loading Components in React Router: A Step-by-Step Guide
Md Yusuf
Posted on September 30, 2024
Lazy loading with React Router is useful for optimizing your React app by loading components only when they are needed, rather than loading everything upfront. You can achieve this using React.lazy
and Suspense
. Here’s an example of how you can implement lazy loading with React Router:
Steps:
- Install React Router (if not already installed):
npm install react-router-dom
- Code Example:
import React, { Suspense, lazy } from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
// Lazy load components
const Home = lazy(() => import('./Home'));
const About = lazy(() => import('./About'));
const Contact = lazy(() => import('./Contact'));
function App() {
return (
<Router>
{/* Suspense allows you to show a fallback (like a loading spinner) while loading */}
<Suspense fallback={<div>Loading...</div>}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
</Suspense>
</Router>
);
}
export default App;
Breakdown:
- React.lazy: This is used to dynamically import the components.
- Suspense: It wraps your routes and shows a fallback component (like a spinner or text) until the lazy-loaded component is ready.
- Routes: Defines the routes that correspond to the lazy-loaded components.
This method improves performance by loading routes and components only when they are accessed, which is great for large applications.
💖 💪 🙅 🚩
Md Yusuf
Posted on September 30, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.