Advanced35 min read

Code Splitting and Lazy Loading

Optimize your application's load time by splitting code and lazy loading components.

Topics Covered:

Code SplittingLazy LoadingReact.lazyDynamic Imports

Prerequisites:

  • Building Custom Hooks

Overview

Code splitting allows you to split your bundle into smaller chunks that load on demand, reducing initial load time.

What is Code Splitting?

Code splitting allows you to split your bundle into smaller chunks. Instead of loading all JavaScript at once, you load only what's needed for the current page or feature.

React.lazy for Component Splitting

React.lazy lets you load components dynamically using dynamic imports. Combine it with Suspense for smooth loading experiences.

Code Example:
import { lazy, Suspense } from 'react';

// Lazy load the component
const Dashboard = lazy(() => import('./Dashboard'));

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

React.lazy creates a separate bundle for the component. Suspense handles the loading state while the component is being fetched.

Route-based Code Splitting

The most common use case is splitting by route. Each route loads its own bundle, reducing initial load time significantly.

Conclusion

Code splitting is essential for large applications. Balance bundle size with user experience.