Code splitting means loading only the part of the app needed for the current route, which improves performance and initial load time.
🧰 Tools to Use
React.lazy()→ to lazy load componentsSuspense→ to show a fallback UI while the component is being loadedreact-router-dom→ for routing
🧠 Step-by-Step Solution
1. Lazy load the components
Instead of importing all components at the top, use React.lazy():
import React, { Suspense, lazy } from "react";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
const Home = lazy(() => import("./pages/Home"));
const About = lazy(() => import("./pages/About"));
const Contact = lazy(() => import("./pages/Contact"));
2. Wrap routes with Suspense
Use Suspense to show a loader or skeleton while the chunk loads:
function App() {
return (
<Router>
<Suspense fallback={<div>Loading...</div>}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
</Suspense>
</Router>
);
}
export default App;
✅ This way, the browser only downloads the JS bundle for the route that’s visited.
3. Optional: Create a Custom Loader
You can use a skeleton or spinner instead of plain text:
<Suspense fallback={<Spinner />}>
{/* routes */}
</Suspense>
🧭 Why this works well
- Reduces initial bundle size.
- Faster page load for users.
- Better performance on slow networks.
- Ideal for large apps with many routes.