React Code splitting using lazy load techniques

Performance optimization is a key factor in modern web development. The load times of our web pages can have a significant impact on user experience, SEO, and even user data consumption. This article will introduce you to the powerful technique of code splitting and lazy loading in React.js, using a common scenario that React developers often encounter.

Understanding the Need for Code Splitting

When developing React applications, it's common for your application to grow over time. Due to the increasing number of modules and components, your application may start to take a significant amount of time to fully load for your users. In such scenarios, a better approach is to break your application code into discrete pieces so that your users can load only the parts they need, when they need them. This is where code splitting comes in.

Code Splitting in React

Let's imagine a simple scenario. You have a React application with a dashboard page and a settings page. We want to split our code so that the chunk of code for the Settings page is only loaded when the user navigates to it. React provides a built-in way to handle this scenario through dynamic imports(). Here's how you would use it:

import React, { lazy, Suspense } from 'react';
import { Route } from 'react-router-dom';

const DashboardPage = lazy(() => import('./DashboardPage'));
const SettingsPage = lazy(() => import('./SettingsPage'));

export default function App() {
  return (
    <>
      <h1>Welcome!</h1>
      <Suspense fallback={<div>Loading...</div>}>
        <Route exact path="/" component={DashboardPage} />
        <Route path="/settings" component={SettingsPage} />
      </Suspense>
    </>
  );
}

We use two key React concepts in our code: React.lazy() and React.Suspense.

React.lazy()

React.lazy() as the name suggests, lets you render a dynamic import as a regular component. It makes it possible to automatically load components only when they are rendered. Our DashboardPage and SettingsPage are imported lazily, which means that these components are only brought in when the corresponding routes are matched.

React.Suspense()

React.Suspense lets you specify a loading indicator in case some components in the tree below it are not yet ready to render. In our case, it serves as a fallback during the time when DashboardPage or SettingsPage is lazily loading.

Wrap Up

Code splitting and lazy loading can dramatically improve the user experience of your React applications. Not only do they help reduce the initial load time, but they also optimize the overall performance of your web application by loading only what is needed. Use these techniques in your React projects and experience the difference for yourself.
Happy coding!