React Lazy Loading is a technique used to optimize performance by splitting your code into smaller bundles and loading components or resources only when they are needed. This improves the initial load time of your application.
Why Use Lazy Loading?
- Performance Improvement: Reduces the initial bundle size by loading parts of the application only when necessary.
- Better User Experience: Faster initial render since less code is downloaded upfront.
React.lazy: The Basics
React provides the React.lazy()
function to dynamically load components when they are rendered.
Syntax
const LazyComponent = React.lazy(() => import('./LazyComponent'));
Example: Lazy Loading a Component
Error Handling with React.lazy
Use an error boundary to catch errors during loading:
import React, { Suspense } from 'react'; const LazyComponent = React.lazy(() => import('./LazyComponent')); class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError() { return { hasError: true }; } render() { if (this.state.hasError) { return <div>Error loading component!</div>; } return this.props.children; } } const App = () => { return ( <ErrorBoundary> <Suspense fallback={<div>Loading...</div>}> <LazyComponent /> </Suspense> </ErrorBoundary> ); }; export default App;
Real-Life Use Case: Lazy Load Routes
Lazy loading is commonly used for route-based splitting in large applications:
import React, { Suspense } from 'react'; import { BrowserRouter as Router, Route, Routes } from 'react-router-dom'; const Home = React.lazy(() => import('./Home')); const About = React.lazy(() => import('./About')); const App = () => { return ( <Router> <Suspense fallback={<div>Loading...</div>}> <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> </Routes> </Suspense> </Router> ); }; export default App;
Best Practices
- Use Granular Splitting: Split components that are less frequently used or heavy.
- Optimize Fallbacks: Provide user-friendly fallbacks (like spinners or placeholders).
- Preload Critical Components: Use
import()
for components you know the user will navigate to soon.