How to speed up React apps with code splitting

Is your React App running too slow or taking too long to load? If that's true, you'll probably resort to code splitting techniques.

Learning how code splitting can improve the performance and speed of your React apps.

Picture 1 of How to speed up React apps with code splitting

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. So 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.

 

Picture 2 of How to speed up React apps with 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 (          

HomePage

           ); }

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 (          

HomePage

           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.

Update 27 June 2023
Category

System

Mac OS X

Hardware

Game

Tech info

Technology

Science

Life

Application

Electric

Program

Mobile