Sobes.tech
Middle+

What does React.lazy do? Is it React.lazy or dynamic import that handles chunking?

sobes.tech AI

Answer from AI

React.lazy is a function that allows you to load React components dynamically, meaning only when they are actually needed, which helps optimize the size of the main bundle.

However, the chunk splitting mechanism is implemented at the module bundler level (for example, Webpack) through dynamic import import(). React.lazy simply wraps this dynamic import, providing a convenient interface for lazy loading components.

Example of usage:

import React, { Suspense } from 'react';

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

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

Here, import('./MyComponent') is a dynamic import that tells the bundler to create a separate chunk for MyComponent. React.lazy takes this import and returns a component that React can render asynchronously.

In summary:

  • Dynamic import is responsible for creating separate chunks.
  • React.lazy provides a convenient way to integrate these chunks into React components with support for Suspense.