REACT Lazy Loading

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'));

Try It Now

Example: Lazy Loading a Component

Here’s how to implement lazy loading with React.lazy and Suspense:

Step 1: Create a Component

Create a simple component to lazy-load:

// LazyComponent.js
const LazyComponent = () => {
  return <div>I am a lazy-loaded component!</div>;
};

export default LazyComponent;

Try It Now

Step 2: Lazy Load the Component

Use React.lazy() and React.Suspense in your main component:

import React, { Suspense } from 'react';

const LazyComponent = React.lazy(() => import('./LazyComponent'));

const App = () => {
  return (
    <div>
      <h1>React Lazy Loading Example</h1>
      <Suspense fallback={<div>Loading...</div>}>
        <LazyComponent />
      </Suspense>
    </div>
  );
};

export default App;

Try It Now

Key Points:

  • React.lazy(() => import('./LazyComponent')): Dynamically imports the component.
  • Suspense: Wraps the lazy-loaded component and provides a fallback UI while it loads.

Lazy Loading Multiple Components

const LazyComponent1 = React.lazy(() => import('./Component1'));
const LazyComponent2 = React.lazy(() => import('./Component2'));

const App = () => {
  return (
    <Suspense fallback={<div>Loading components...</div>}>
      <LazyComponent1 />
      <LazyComponent2 />
    </Suspense>
  );
};

Try It Now

 

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;

Try It Now

 

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;

Try It Now

Best Practices

  1. Use Granular Splitting: Split components that are less frequently used or heavy.
  2. Optimize Fallbacks: Provide user-friendly fallbacks (like spinners or placeholders).
  3. Preload Critical Components: Use import() for components you know the user will navigate to soon.