Skip to content

Maheshwaran1303/Code-Spliting-Lazy-Loading---React

Repository files navigation


React Lazy Loading Demo

A practical React project demonstrating route-based and button-triggered lazy loading using React.lazy, Suspense, and React Router v6. Tailwind CSS is used for styling.


Features

  • Route-based Lazy Loading: Components (Home, About, Contact) are lazy-loaded when navigating via React Router routes.

  • Button-based Lazy Loading: Components can also be loaded on-demand when the user clicks buttons.

  • Suspense Fallbacks: Displays a fallback UI while lazy-loaded components are being fetched.

  • Clean & Modern UI: Uses Tailwind CSS for a responsive and clean design.


Project Structure

src/
├── App.jsx             # Main app with routing and lazy loading
├── pages/
│   └── Home.jsx        # Home page component
└── components/
    ├── About.jsx       # About component (lazy-loaded)
    └── Contact.jsx     # Contact component (lazy-loaded)


Installation

  1. Clone the repository:
git clone https://github.com/Maheshwaran1303/Code-Spliting-Lazy-Loading---React

  1. Install dependencies:
npm install

  1. Run the development server:
npm run dev

  1. Open your browser and go to http://localhost:5173

How It Works

1. Route-based Lazy Loading

  • React.lazy() dynamically imports components only when their route is accessed.

  • Suspense shows a fallback while the component is being loaded.

const About = React.lazy(() => import("./components/About"));
<Route path="/about" element={<About />} />

2. Button-based Lazy Loading

  • Components can be lazy-loaded manually when the user clicks a button.

  • Useful for rendering heavy components on-demand.

const LazyContact = React.lazy(() => import("./components/Contact"));
{showContact && <LazyContact />}

3. Suspense Fallback

  • Any lazy-loaded component must be wrapped with Suspense.

  • A fallback UI is shown until the component is loaded.

<Suspense fallback={<p>Loading component...</p>}>
  {showAbout && <LazyAbout />}
</Suspense>


Dependencies

  • React 18

  • React Router v6

  • Tailwind CSS (for styling)


Tailwind CSS Setup

  1. Install Tailwind CSS:

Learning Outcomes

  • Understand lazy loading in React for both routes and components.

  • Learn to use React.Suspense and fallback UIs.

  • Combine React Router v6 with dynamic imports.

  • Apply Tailwind CSS for fast, responsive styling.

  • Improve performance by loading components only when needed.


License

MIT License © 2025


Releases

No releases published

Packages

No packages published