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.
-
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.
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)
- Clone the repository:
git clone https://github.com/Maheshwaran1303/Code-Spliting-Lazy-Loading---React
- Install dependencies:
npm install
- Run the development server:
npm run dev
- Open your browser and go to http://localhost:5173
-
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 />} />
-
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 />}
-
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>
-
React 18
-
React Router v6
-
Tailwind CSS (for styling)
- Install Tailwind CSS:
-
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.
MIT License © 2025