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
- How to build a QR Code generator using React
- 5 best free CSV splitting tools, CSV file splitting software
- 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
- How to manage state in React using Jotai
- 10 most used free hard drive splitting software in 2023
Maybe you are interested
GitHub Copilot is now available for free in VS Code
Latest Sword Master Story Code and How to Enter Code
Latest Roblox Clicker Simulator Codes 12/2024
Ninja Team Code: Ninja Village 3D latest and how to redeem code
Full Giftcode Blue Lock Rivals Roblox latest and how to redeem code
Latest Anime Squad Simulator Codes and How to Enter Codes