How to Speed Up React Apps With Code Splitting


Is your React application too slow or taking too long to load? If so, you might want to use a technique known as code splitting. This technique is very effective at improving the load speed and performance of React applications. But what is code splitting? And how is it done?

What Is Code Splitting?

A typical React application comprises dozens of components (and code). But you don’t need to load most of these components when you load them for the first time. Code splitting entails splitting out the different parts of your application and only loading them when needed. This is far more efficient than loading the entire application at once.


Consider a React application that has three pages: the homepage, the about page, and the products page. When you’re on the homepage, there’s no point in loading the about page or the products page. Because you’re not actually on those pages yet. The idea of code splitting is to make sure you load the code only when it’s needed.

Man using both a laptop and a phone

Open a webpage on your web browser, and then open the DevTools (you can click F12 on your keyboard to open it on Google Chrome). Next, go to the Source tab. There you’ll find all the code that’s downloaded as you navigate to the page. Without code splitting, the browser downloads all the files in your project on the initial page load. This can slow down your website if it contains a lot of files.

Code splitting becomes especially useful as your project starts to get larger and larger. This is because downloading the entire application files at once can take a very long time. So splitting that up is going to be quite beneficial.

The best part about code splitting is that you can delay the loading of components as well as functions. Our introductory guide on ReactJS explains components and functions in-depth in case you need a refresher.

Code Splitting Functions: Using Dynamic Import

Consider the following situation. You want your homepage to have a button. When you click the button, you want to alert the sum of 2 and 2 (which is 4). So you create a Home.js component and define the view of your homepage.

In this case, you have two options. First, you can import the code for adding the numbers at the top of the Home.js file. But here’s the problem. If you were to import the function at the top of the file, then the code will load even when you haven’t clicked the button. A better approach will be to load the sum() function only when you click the button.

To achieve this, you’ll need to perform a dynamic import. This means that you’ll import the sum() function inline in the button element. Here’s the code for the same:

 export default function Home() { 
return (
   <div className="Home">
     <button onClick={() => {
       import("../sum.js").then((module) => {
         alert(module.sum(2, 2))
       Sum both numbers

Now the browser will only download the sum.js module when you click the button. This improves the loading time of the homepage.

Code Splitting Components: Using React.lazy and Suspense

You can split components in React using the lazy() function. The best place to perform code splitting would be inside your router. Because this is where you map components to routes in your application. You can read our guide on how to build a single-page app with React Router if you need a refresher.

Let’s suppose that your app has a Home, About, and Products component. When you’re at the Home component, there’s no point in loading the About component or the Products component. So you need to split them away from the Home route. The following code demonstrates how to achieve that:

First, you need to import the required functions and components from the react and react-router-dom modules:

 import { Routes, Route, Outlet, Link } from "react-router-dom";
import { lazy, Suspense } from "react";

Next, you need to import the components dynamically using the lazy() function:

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

Next, set up the layout (navigation menu). Use the <Outlet /> component to render the component that corresponds to the current route (Home, About, or Products component):

 function NavWrapper() {
  return (
      <nav style={{ display: "flex", gap: "1rem" }}>
        <Link to="">Home</Link>
        <Link to="/about">About</Link>
        <Link to="/products">Products</Link>
      <Suspense fallback={<h1>Loading...</h1>}>
        <Outlet />

You can see that we wrap the components inside <Suspense />. This tells React that everything inside <Outlet /> has the potential to be lazily loaded, which means that it might not be available right away. For this reason, the Suspense component has a fallback property. In our case, the value is simple text that says “Loading…”. So while each of the pages is being downloaded, it’s going to say loading on the screen.

Finally, set up the route:

 export default function App() {
  return (
      <Route path="" element={<NavWrapper />}>
        <Route path="" element={<Home />} />
        <Route path="/products" element={<Products />} />
        <Route path="/about" element={<About />} />

Now when you visit the homepage, the browser loads only the Home.js file. In the same way, when you click on the About link in the navigation menu to visit the About page, the browser loads only the About.js file. This is the same for the Products page.

Conditional Code Splitting

Oftentimes you may have content on your page that is only applicable to certain users. For example, on your homepage, you can have a section with admin data that is exclusive to admin users. This could be an admin dashboard that shows up for admin users, but not for normal users.

In this case, you wouldn’t want to show all of that data every single time. In this case, you can use the code-splitting technique to make sure you only show that information if this person is an admin.

Here’s what that code would look like:

 import { lazy, Suspense } from "react";
const AdminData = lazy(() => import("./AdminData"));

export default function Home() {
  const [isAdmin, setIsAdmin] = useState(false)

  return (
   <div className="Home">
     <button onClick={() => setIsAdmin(prev => !prev)}>
       Toggle Admin

    <Suspense fallback={<h1>Loading...</h1>}>
      {isAdmin ? <AdminData /> : <h2> Not the Admin </h2>}

Now, when you click the toggle button, isAdmin will be set to true. As a result, the app will show the <AdminData> that is being lazily loaded. But if you’re not an admin user, then the app will never download AdminData.js because it’s not going to need it.

Conditional code splitting uses the same concept as conditional rendering in React.

Advanced Code Splitting Concepts

One advanced technique you can enable when splitting code is transitions. The useTransition() hook allows you to do non-urgent updates which won’t change your UI until they’re finished updating.

First, you import the hook:

 import {useTransition} from "react" 

Then you call the hook, which returns isPending and startTransition:

 const [isPending, startTransition] = useTransition()

Finally, wrap the code for updating your state inside startTransition():

 startTransition(() => {
  setIsAdmin((prev) => !prev)

Now your actual UI is not going to display the fallback value (the loading text) until the browser finishes the transition. This means that it’s going to wait for the browser to download the entire admin data before it tries to show any data at all.

Other Ways to Optimize React Performance

This article covered code splitting as a method for improving the performance of your React applications. But there are several other methods as well that can give you the required knowledge to create robust applications.

Las Vegas News Magazine

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More