DEV Community

Md Yusuf
Md Yusuf

Posted on

Lazy loading and code splitting in React

Lazy loading and code splitting in React help optimize performance by loading only the necessary parts of your application, reducing initial load times. Here's how they work:

1. Lazy Loading

Lazy loading defers the loading of components until they are needed. In React, this is done using React.lazy() and Suspense.

import React, { Suspense } from 'react';

const LazyComponent = React.lazy(() => import('./LazyComponent'));

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

export default App;
Enter fullscreen mode Exit fullscreen mode
  • React.lazy(): Dynamically imports a component.
  • Suspense: Renders a fallback (e.g., a loading indicator) while the lazy-loaded component is being fetched.

2. Code Splitting

Code splitting breaks your bundle into smaller chunks, loading them on-demand. Webpack, used by React’s build system, automatically creates split points.

  • Dynamic Imports: You can use dynamic import() to load modules only when needed. For example:
import("./module").then(module => {
  // Use the dynamically loaded module
});
Enter fullscreen mode Exit fullscreen mode
  • React Router and Code Splitting: When using React Router, lazy load route components for better performance.
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import React, { Suspense } from 'react';

const Home = React.lazy(() => import('./Home'));
const About = React.lazy(() => import('./About'));

function App() {
  return (
    <Router>
      <Suspense fallback={<div>Loading...</div>}>
        <Switch>
          <Route path="/about" component={About} />
          <Route path="/" component={Home} />
        </Switch>
      </Suspense>
    </Router>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Benefits:

  • Improved Load Time: Only the necessary code is loaded when required.
  • Optimized Performance: Code splitting ensures that users only download the parts of the app they interact with.

Would you like a practical example or help implementing this in your project?

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more