DEV Community

TenE
TenE

Posted on

Optimize React Rendering with Lazy Loading and Code Splitting

Introduction

Code splitting is a technique that improves the performance of React applications by breaking the bundle into smaller chunks that are loaded only when needed. This helps reduce the initial load time and enhances the user experience.

Why Use Code Splitting?

  • Improved Performance: Reduces initial JavaScript payload size.
  • Faster Load Times: Loads only necessary code when required.
  • Efficient Resource Utilization: Minimizes unused code execution.

Implementing Code Splitting in React

React provides built-in support for code splitting via lazy and Suspense.

1. Using lazy for Lazy Loading

  • The React.lazy or lazy function allows you to load a component dynamically only when it is needed. Example:
import React, { Suspense, lazy } from "react";
const LazyComponent = lazy(() => import("./LazyComponent"));

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

export default App;
Enter fullscreen mode Exit fullscreen mode

2. Code Splitting with React Router

When using React Router, you can split code by dynamically importing route components.

Example:

import React, { Suspense, lazy } from "react";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";

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

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

export default App;
Enter fullscreen mode Exit fullscreen mode

3. Using Webpack's Dynamic Imports

Webpack supports dynamic imports using import(), which can be used to split code.

Example:

function loadComponent() {
  import("./DynamicComponent").then((module) => {
    const Component = module.default;
    // Render component dynamically
  });
}
Enter fullscreen mode Exit fullscreen mode

Best Practices for Code Splitting

  • Split at Route Level: Load components dynamically for different pages.
  • Lazy Load Large Dependencies: Use lazy for libraries like charts or modals.
  • Optimize Bundle Splitting: Use Webpack's SplitChunksPlugin for optimized splitting.
  • Use Suspense for Fallback UI: Provide user-friendly loading indicators.

Conclusion

Code splitting is an essential technique to improve performance in React apps. By leveraging lazy, Suspense, and dynamic imports, you can enhance the user experience by reducing initial load times and loading components efficiently.

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly — using the tools and languages you already love!

Learn More

Top comments (0)

ACI image

ACI.dev: The Only MCP Server Your AI Agents Need

ACI.dev’s open-source tool-use platform and Unified MCP Server turns 600+ functions into two simple MCP tools on one server—search and execute. Comes with multi-tenant auth and natural-language permission scopes. 100% open-source under Apache 2.0.

Star our GitHub!

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay