Clear, practical technology insights BSOD Code Lookup · Windows Error Code Lookup · Wi-Fi Troubleshooting · PC Troubleshooting Checklist

How to Speed Up React Apps with Code Splitting

Learn about Code Splitting, including what Code Splitting is, key uses, practical steps, common issues, and answers to frequently asked questions.

Table of Contents

This practical guide explains how to speed up react apps with code splitting with clear steps and useful context. It also covers common requirements, potential problems, and the details that can help you get better results.

Code Splitting guide image 1

Is your React App running too slow or taking too long to load? If so, you may need to resort to code splitting techniques. This technique is very effective in improving the loading speed and performance of React applications. What is code splitting? How to use it?

What Is Code Splitting?

A typical React application consists of dozens of components and code. However, you don't need to download them all the first time you use them. Code splitting entails separating different parts of the application and loading them only when needed. This is much more efficient than loading the entire application at once.

For example, an app has 3 pages: homepage, about page, products page. Once on the home page it makes no sense to load both the about page and the products page since you're not actually on those pages, the idea of code splitting is to make sure you only load the necessary code.

The best part of code splitting is that you can delay the loading of components and their functions.

What Is Code Splitting? - Code Splitting

Code Splitting Function: Using Dynamic Import

Consider the following situation. You want the homepage to have a button click. When the button is clicked, you want to announce the sum of 2 plus 2. So you create Home.js and define a home page view.

In this case, you have two options. First, you can enter the code to add the number at the top of the Home.js file. However, here comes the problem. If you enter this function at the top of the file, the code will load even if you haven't clicked the button. A better approach is to load the sum() function only when you click that button.

To achieve this, you need to implement dynamic import. That means you will enter the sum() function inline in the button element. Here is the code:

export default function Home() { ?return ( ??? ?????
 ????? ?? ?); }

Note, this browser will only load the sum.js module when you click the button. This improves the loading time of the homepage.

Splitting Code Components: Using React.lazy and Suspense

You can separate components in React using the lazy() function. The best place to do code splitting is inside the router because this is where you map components to routes in your application.

Let's say your app has Home, About and Products. When at Home, it makes no sense to download About or Products. Therefore, you need to separate them from the Home route. The following code illustrates how to achieve that:

First, import the necessary 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, import the dynamic components 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). Used to output the component corresponding to the current route (Home, About or Products):

function NavWrapper() { ??return ( ????<> ??????
 ??????Loading.}> ???????? ?????? ???? ??); }

You can see the components wrapped in. This tells React that everything inside is potentially slow to load. Therefore, the Suspense element has a fallback attribute. In that case, the value is plain text saying 'Loading.' . While each page is loading, you will receive a loading message on the screen.

Finally, set up the route:

export default function App() { ??return ( ???? ??????}> ????????} /> ????????} /> ????????} /> ?????? ???? ??); }

Now when accessing this homepage, the browser only downloads the file Home.js . Similarly, when clicking the About link in the navigation menu to access the About page, the browser only downloads the About.js file. This is similar to the Products page.

Code Splitting by Condition

Sometimes you have some content on your site that is only relevant to certain users. For example, on the homepage, you have a section that contains admin data only for admins. It might be an admin panel not for regular users.

In this case, you won't want to show all that data every time it loads. You can use code splitting techniques to make sure that information is only visible to admin users.

The code block will look like this:

import { lazy, Suspense } from "react"; const AdminData = lazy(() => import("./AdminData")); export default function Home() { ??const [isAdmin, setIsAdmin] = useState(false) ??return ( ??? ?????
 ????? ????Loading.}> ??????{isAdmin ? :

Not the Admin

} ???? ?? ?); }

Now when the toggle button is clicked, isAdmin will be set to true. As a result, the app will currently load slowly. However, if you are an admin, the app will never load AdminData.js because the app won't need it.

Advanced Code Splitting Concepts

One advanced technique you can enable when splitting code is forwarding. The useTransition() hook allows you to perform emergency updates that will not change the UI until they have finished updating.

First, import the hook:

import {useTransition} from "react"

Then call the hook that returns isPending and startTransition :

const [isPending, startTransition] = useTransition()

Finally close the code to update the state inside startTransition():

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

Now your actual UI won't show the fallback value until the browser finishes transitioning. That means it will wait for the browser to load all of the admin data before trying to display any data.

Here's everything you need to know about how to speed up your React app with code splitting. Hope the article is useful to you.

Conclusion

Understanding Code Splitting makes it easier to compare options, avoid common mistakes, and apply the information in this guide more effectively. Review the relevant requirements before making changes or choosing a solution.

FAQ

How do you speed up react apps with code splitting?

Follow the steps in this guide in order, confirm the required settings or tools, and verify the result before making additional changes.

Is it safe to speed up react apps with code splitting?

It is generally safe when you follow the recommended instructions, use trusted tools, and avoid changing settings you do not understand.

What should you do if the process does not work?

Recheck the requirements, restart the device or application when appropriate, and review each step for missed settings or compatibility issues.

Discussion

Reader Comments 0

Sign in with email or Google to join the discussion.