As your React application grows, loading everything up front can slow down performance and hurt user experience. Code splitting allows you to load only what's needed, improving responsiveness. In this article, we’ll explore dynamic component loading using React.lazy and Suspense.

Step 1: Static vs Dynamic Imports

Normally, components are imported statically:

import HeavyComponent from './HeavyComponent';

This means HeavyComponent is bundled into the main JS file, even if the user never visits the route or sees the component.

Step 2: Dynamic Import With React.lazy

To prevent that, use React.lazy with Suspense:

import { Suspense, lazy } from 'react';

const HeavyComponent = lazy(() => import('./HeavyComponent'));

function App() {
  return (
    Loading...