Blog>
Snippets

Dynamically Importing Components with React.lazy and Next.js Suspense

Showcase how to dynamically import a component using React.lazy and Suspense in a Next.js application for better performance.
import React, { Suspense } from 'react';

// Dynamically import the LazyComponent using React.lazy
const LazyComponent = React.lazy(() => import('./path/to/LazyComponent'));

function MyComponent() {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        {/* The LazyComponent will only load when it's needed, reducing the initial bundle size */}
        <LazyComponent />
      </Suspense>
    </div>
  );
}

export default MyComponent;
This code demonstrates the use of React.lazy to dynamically import a component named 'LazyComponent' from a specified path and render it within a Suspense component. The Suspense component allows you to specify a fallback UI to show while the LazyComponent is being loaded. This improves performance by only loading the LazyComponent when it is needed.