How to speed up React apps with code splitting
Learning how code splitting can improve the performance and speed of your React apps.
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.
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.
You should read it
- Best React Usages in 2023
- 6 best free tutorials to learn about React and create web applications
- How to detect clicks outside a React component using a custom hook
- How to use Sass in React
- How to manage date and time in React using Moment.js
- 10 professional code sample websites for programmers
- Tooltip creation tools are useful with ReactJS
- React mistakes to avoid for successful app development
May be interested
- React mistakes to avoid for successful app developmentreact is a popular framework that is easy to learn but also easy to make mistakes when programming if you are not careful. here are common react mistakes that you might make during app development.
- How to create a Hacker News clone using Reactare you looking to upgrade your react programming skills? then try to build your own version of hacker news with the help of the guide below.
- 9 malicious applications on Google Play, if installed, should be removed immediatelyrecently, trend micro security researchers discovered a series of optimization applications, speeding up phones on google play containing androidos_badbooster.hrx malware.
- How to create a swipeable interface in a React app using Swiperswiper is a flexible library that allows you to create swipeable interfaces in react applications. let's explore how to create a swipeable interface in a react app using swiper!
- 10 professional code sample websites for programmersmost programmers have to do a lot of different tasks. knowing where to find free code samples online will help you learn and create applications.
- How to build a CRUD to-do list app and manage its state in Reactwhen managing complex state in the next app, things can get tricky. however, you can overcome it by learning the fundamentals of react and managing state through this classic app.
- Series of Android applications contain malicious code you should remove immediately from your devicecybersecurity researchers have discovered many android apps containing adware and information-stealing malware on the google play store.
- Latest Legends of Speed code and how to enter the codelegends of speed codes are usually valid for a long time. however, in some cases they will have limits such as input limits or code time limits.
- 6 best code editor apps for Macwhether you are a script writer or a black hat hacker, a programmer or professional code writer, you need a code editor application. if you choose to program on a mac instead of windows, here is a list of the best code editing tools you should use.
- Instructions for creating a Tic-Tac-Toe game using React-Nativelearning how to develop a tictactoe game allows you to learn basic styling, user interaction, and more. all will help you improve the basic foundation in react-native.