Lazy Loading with React.lazy

Loading

Lazy loading is a technique in React that allows you to load components only when they’re needed, improving your application’s initial load performance. React provides the React.lazy function to implement this pattern easily.

Basic Usage

import React, { Suspense } from 'react';

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

function MyComponent() {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        <LazyComponent />
      </Suspense>
    </div>
  );
}

Key Points

  1. React.lazy():
  • Takes a function that returns a dynamic import()
  • Returns a component you can render in your JSX
  1. Suspense:
  • Required wrapper for lazy components
  • Provides a fallback prop to show while the component is loading
  1. Error Boundaries:
  • It’s good practice to wrap lazy components with error boundaries to handle loading failures

Route-based Code Splitting Example

A common use case is lazy loading routes:

import React, { Suspense } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

const Home = React.lazy(() => import('./routes/Home'));
const About = React.lazy(() => import('./routes/About'));

function App() {
  return (
    <Router>
      <Suspense fallback={<div>Loading...</div>}>
        <Switch>
          <Route exact path="/" component={Home} />
          <Route path="/about" component={About} />
        </Switch>
      </Suspense>
    </Router>
  );
}

Named Exports

For components using named exports, you need to re-export them as default:

// SomeComponent.js
export function SomeComponent() { /* ... */ }

// In another file
const SomeComponent = React.lazy(() => 
  import('./SomeComponent').then(module => ({ default: module.SomeComponent }))
);

Limitations

  • Currently only works with default exports
  • Doesn’t support server-side rendering (SSR) out of the box
  • Requires Suspense boundary

Lazy loading is a powerful tool for optimizing React applications, especially large ones with many components or routes.

Leave a Reply

Your email address will not be published. Required fields are marked *