DEV Community

Navin Prasad
Navin Prasad

Posted on • Originally published at codelila.com on

Implementing Code Splitting in React for Improved Performance

Introduction

In today’s fast-paced digital landscape, where users demand lightning-fast experiences, web developers face a pressing challenge: how to create web applications that are not only feature-rich but also load quickly. When it comes to React applications, one powerful technique that can significantly enhance performance is code splitting.

Imagine this scenario: You’re building a large-scale React application with numerous components, libraries, and features. Traditionally, all of your JavaScript code is bundled into a single massive file. As a result, when a user lands on your site, they have to wait for this behemoth of a bundle to download and execute before they can interact with your app. This can lead to frustratingly long loading times, especially on slower connections or less powerful devices.

This is where code splitting comes to the rescue. Code splitting is a strategy that allows you to break down your application’s JavaScript bundle into smaller, more manageable pieces. Instead of loading everything upfront, you can load only the code that’s necessary for the current user’s journey through your app. This not only dramatically reduces the initial load time but also optimizes the overall performance of your React application.

In this blog post, we’ll explore the concept of code splitting in React and dive into various techniques and best practices for its implementation. Whether you’re working on a massive enterprise-level application or a smaller project, understanding code splitting can be a game-changer for your development workflow and user experience. So, let’s embark on this journey to harness the power of code splitting and ensure that your React applications are not just feature-rich but also blazingly fast. Let’s get started!

Step 1: Set Up Your Development Environment

Before you start, make sure you have Node.js and npm (Node Package Manager) installed on your system. You can download them from the official website if you haven’t already.

Step 2: Create a New React Project

Open your terminal and run the following command to create a new React project with Create React App:

npx create-react-app code-splitting-example

Enter fullscreen mode Exit fullscreen mode

Once you the above command completes, you may have the output similar to below.

Step 3: Navigate to Your Project Directory

Navigate to your project directory using the following command:

cd code-splitting-example

Enter fullscreen mode Exit fullscreen mode

Step 4: Open the project directory in vscode

Open the project directory in vscode using the following command:

code .
Enter fullscreen mode Exit fullscreen mode

You should see the project structure as below.

Step 4: Create Some Sample Components

In this step, you can create some sample components that you’ll later split into separate bundles. For example, let’s create “components” directory in src and then create two components named Home.js and About.js inside a components directory:

Create and update src/components/Home.js:

import React from 'react';

function Home() {
  return (
    <div>
      <h1>Welcome to the Home Page!</h1>
    </div>
  );
}

export default Home;

Enter fullscreen mode Exit fullscreen mode

Create and update src/components/About.js:

import React from 'react';

function About() {
  return (
    <div>
      <h1>About Us</h1>
      <p>We are a passionate team of developers.</p>
    </div>
  );
}

export default About;

Enter fullscreen mode Exit fullscreen mode

Step 5: Create a Sample Routing Structure

npm install react-router-dom

Enter fullscreen mode Exit fullscreen mode

You should see similar output as below:

Now, create a simple routing structure. Edit src/App.js:

import React from 'react';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import Home from './components/Home';
import About from './components/About';

function App() {
  return (
    <Router>
      <div>
        <nav>
          <ul>
            <li>
              <Link to="/">Home</Link>
            </li>
            <li>
              <Link to="/about">About</Link>
            </li>
          </ul>
        </nav>

        <hr />

        <Route exact path="/" component={Home} />
        <Route path="/about" component={About} />
      </div>
    </Router>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

Step 6: Implement Code Splitting

To implement code splitting, we can use the React.lazy() function. Modify src/App.js to use React.lazy() for loading the components:

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

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

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

export default App;

Enter fullscreen mode Exit fullscreen mode

Step 7: Start the Development Server

You’re all set! Now, start your development server:

npm start

Enter fullscreen mode Exit fullscreen mode

This will launch your React application, and you can navigate between the “Home” and “About” pages. Code splitting is automatically applied, and each component will be loaded on-demand when you access its respective route.

You’ve now created a simple React project named “code-splitting-example” that demonstrates code splitting using React.lazy() and React Router. You can expand on this project by adding more components and experimenting with different code splitting scenarios to showcase its benefits further.

Summary

In the fast-paced world of web development, optimizing React applications for speed and responsiveness is essential. Code splitting offers a powerful solution. It breaks down the JavaScript bundle into smaller parts, loading only what’s needed for improved performance.

Key Takeaways:

  • Code Splitting Benefits: Code splitting reduces initial load times, making web applications more responsive.
  • When to Use It: Code splitting is ideal for large apps, complex routing, and dynamic imports.
  • Techniques: We explored dynamic imports with import() and how to use React.lazy() with <Suspense> for code splitting.
  • Best Practices: Follow component grouping, Webpack optimization, and error handling for effective code splitting.

Code splitting empowers developers to strike the right balance between feature-rich applications and exceptional performance, delivering an elevated user experience.

The post Implementing Code Splitting in React for Improved Performance appeared first on CodeLila.

Top comments (0)