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.
Top comments (2)
Let me see if I understood.
All the components of the application will be loaded at once on the initial bundle if you don't configure the lazy loading, right? Even though the route for the component doesn't matches?
Also, just to mention, you need to export the lazy loaded components as default exports instead of named exports.
export function Home() // wrong
export default function Home() // right