DEV Community

Pramod
Pramod

Posted on

๐Ÿš€ Code Splitting in React with Lazy Loading

๐Ÿš€ Code Splitting in React with Lazy Loading

As React apps grow, so do their bundle sizes. Loading everything at once can slow down performance and hurt user experience. Thatโ€™s where code splitting and lazy loading come in.

In this blog, weโ€™ll explore how to split your code and load components only when needed using React.lazy and Suspense.


๐Ÿ’ก What is Code Splitting?

Code splitting means breaking up your JavaScript bundle into smaller chunks that can be loaded on demand.

Benefits:

  • ๐Ÿš€ Faster initial page loads
  • ๐Ÿšฎ Less unused code
  • ๐Ÿ” Better performance for large apps

React supports code splitting out of the box using dynamic import() and React.lazy().


๐ŸŒ Basic Example with React.lazy

import React, { lazy, Suspense } from 'react';

const AboutPage = lazy(() => import('./pages/About'));

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

export default App;
Enter fullscreen mode Exit fullscreen mode

๐Ÿ” Explanation:

  • lazy() dynamically loads the component.
  • Suspense shows a fallback UI (like a spinner) until the component is loaded.

๐Ÿ“Œ Best Practices

  1. Use lazy loading for non-critical components like modals, settings pages, charts, etc.
  2. Combine with React Router for route-based code splitting.
  3. Keep fallbacks lightweight to avoid delays.

๐Ÿ—บ๏ธ Real-World Use with React Router

import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
const Home = lazy(() => import('./pages/Home'));
const Profile = lazy(() => import('./pages/Profile'));

function App() {
  return (
    <Router>
      <Suspense fallback={<div>Loading page...</div>}>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/profile" element={<Profile />} />
        </Routes>
      </Suspense>
    </Router>
  );
}
Enter fullscreen mode Exit fullscreen mode

๐ŸŽ‰ Bonus: Named Exports with React.lazy

React.lazy only works with default exports. If your component uses named exports, wrap it:

const LazyComponent = lazy(() =>
  import('./MyComponent').then(module => ({ default: module.MyComponent }))
);
Enter fullscreen mode Exit fullscreen mode

๐Ÿš€ Final Thoughts

Code splitting and lazy loading are essential for improving performance in large-scale React apps. They help reduce load time, enhance UX, and boost Lighthouse scores!

Start small: lazy load routes, then explore loading components, utilities, or charts on demand.


๐Ÿ”— Useful Links

Thanks for reading! ๐Ÿ‘‹ Feel free to share or comment with questions!

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.