Code Splitting and Lazy Loading

React.js 114 views Nov 05, 2025 2 min read

Code splitting and lazy loading are techniques used to improve performance by loading only the code that is needed, when it is needed. This reduces the initial bundle size and speeds up page load time.


What is Code Splitting?

Code splitting breaks your application into smaller JavaScript bundles instead of loading everything at once.

Benefits:

  • Faster initial load

  • Better performance on slow networks

  • Improved user experience


What is Lazy Loading?

Lazy loading loads components only when they are rendered, rather than at app startup.


React Lazy Loading Basics

React provides React.lazy() and Suspense for lazy loading components.


Basic Example

import React, { Suspense } from "react"; const Dashboard = React.lazy(() => import("./Dashboard")); function App() { return ( <Suspense fallback={<p>Loading...</p>}> <Dashboard /> </Suspense> ); }
  • React.lazy() dynamically imports a component

  • Suspense shows fallback UI while loading


Lazy Loading Routes (React Router)

import { Routes, Route } from "react-router-dom"; const Home = React.lazy(() => import("./pages/Home")); const About = React.lazy(() => import("./pages/About")); function App() { return ( <Suspense fallback={<p>Loading page...</p>}> <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> </Routes> </Suspense> ); }

Multiple Lazy Components

<Suspense fallback={<Spinner />}> <ComponentA /> <ComponentB /> </Suspense>

Error Boundaries (Recommended)

Lazy loading can fail (e.g., network issues). Use error boundaries.

class ErrorBoundary extends React.Component { state = { hasError: false }; static getDerivedStateFromError() { return { hasError: true }; } render() { return this.state.hasError ? <p>Something went wrong</p> : this.props.children; } }

Dynamic Imports Without React.lazy

For non-components:

const module = await import("./utils/math");

Best Practices

  • Lazy load routes and large components

  • Do not lazy load small, frequently used components

  • Use meaningful fallback UI

  • Combine with code splitting by routes

Some advanced sections are available for Registered Members
Share this Post
🚀 Want to Test Your Knowledge?

Take quizzes related to this topic and see where you stand!

Start Quiz Now
Back to Tutorials