Open In App

How to improve slow React application rendering ?

Last Updated : 07 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Slow React application rendering as its name suggests is a small or large delay in rendering elements. There may be multiple reasons for that. React uses the concept of Virtual DOM. All the elements in React are rendered using the render method in which we have to provide an id of an element (mostly div) to be rendered. Every element in React is immutable. Hence, to Update the element, we have to call the Render method again.

Prerequisites:

Approach to Improve Slow React Application Rendering:

Slow React Application Rendering may occur due to heavy components, images, bad code practices unnecessary renders due to changes in states. This problem can be reduced by code splitting, avoiding unnecessary re-renders and memoization. We will be using useMemo hook to reduce calculations and updates to improve rendering.

Steps to create React Application

Step 1: Create a React application using the following command:

npx create-react-app useMemo 

Step 2: After creating your project folder i.e. useMemo, move to it using the following command:

cd useMemo

Project Structure:

Example 1: This example uses useState hook to store and update state and render on UI.

Javascript




// Filename - App.js
 
import { useState } from "react";
import "./App.css";
 
export default function App() {
    // 1st counter state
    const [counter1, setCounter1] = useState(0);
 
    // 2nd counter state
    const [counter2, setCounter2] = useState(0);
 
    // Sample Heavy Calculation Function
    const heavyCalculation = () => {
        let i = 0;
        for (let outer = 0; outer < 10000; outer++) {
            for (let temp = 0; temp < 10000; temp++) {
                while (i < 10000) i++;
            }
        }
        return counter1 % 2 === 0 ? true : false;
    };
 
    return (
        <div className="App">
            {heavyCalculation()
                ? `Counter is even with value ${counter1}`
                : `Counter is odd with value ${counter1}`}
            <br />
            <button
                onClick={() => {
                    setCounter1(counter1 + 1);
                }}
            >
                Increment counter1
            </button>
            <br />
            Counter 2 is {counter2}
            <br />
            <button
                onClick={() => {
                    setCounter2(counter2 + 1);
                }}
            >
                Increment counter2
            </button>
        </div>
    );
}


Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

Here, in the output, a heavy function is being called on Rendering. Now even though it is being used for the first counter, but it still causes render due to counter2 slow.

Example 2: This example implements useMemo Hook to avoid unnecessary update and hence reduce rerenders on the UI.

App.js




import { useState, useMemo } from "react";
import "./App.css";
 
export default function App() {
 
  // 1st counter state
  const [counter1, setCounter1] = useState(0);
 
  // 2nd counter state
  const [counter2, setCounter2] = useState(0);
 
  // Our custom useMemo Function
  const useMemoFunction = useMemo(() => {
    let i = 0;
    for (let outer = 0; outer < 10000; outer++) {
      for (let temp = 0; temp < 10000; temp++) {
        while (i < 10000) i++;
      }
    }
    return counter1 % 2 === 0 ? true : false;
  }, [counter1]);
 
  return (
    <div className="App">
      {useMemoFunction
        ? `Counter is even with value ${counter1}`
        : `Counter is odd with value ${counter1}`}
      <br />
      <button
        onClick={() => {
          setCounter1(counter1 + 1);
        }}
      >
        Increment counter1
      </button>
      <br />
      Counter 2 is {counter2}
      <br />
      <button
        onClick={() => {
          setCounter2(counter2 + 1);
        }}
      >
        Increment counter2
      </button>
    </div>
  );
}


Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

Here, heavy functionality is used by useMemo hook containing counter1 as a dependency. Due to this Counter1 still shows delay, but it does not affect the performance of counter2.



Similar Reads

Server Side Rendering vs Client Side Rendering vs Server Side Generation
In the world of web development, there are several approaches to rendering web pages: server-side rendering, client-side rendering, and server-side generation. Each approach has its own advantages and disadvantages, and choosing the right one for your project depends on your specific needs and goals. In this blog, we’ll explore the differences betw
4 min read
Explain lifecycle of component re-rendering due to re-rendering of parent component
React is a javascript library that renders components written in JSX. You can build and render any component as per your usage. States can be updated accordingly using the setState method. Props can be updated only by the parent component. Updating of state and props leads to the rendering of UI. Different lifecycle methods are called during these
2 min read
How does SSR(Server-Side Rendering) differ from CSR(client-side rendering) ?
Server-Side Rendering (SSR) and Client-Side Rendering (CSR) are two different approaches used in web development to render web pages to users. Each approach has its own set of advantages and disadvantages. In this article, we will learn about the difference between SSR and CSR with examples and features. Table of Content Server-Side Rendering (SSR)
4 min read
How to Use React Suspense to Improve your React Projects ?
Suspense is a React component used to suspend the rendering process to perform some asynchronous tasks like getting data from API or loading any other component lazily. In simple words, Suspense is like waiting for something to happen, where we are not sure when it will happen. Suspense is beneficial in code splitting and data fetching processes. W
3 min read
How to Fix a Slow WordPress Website ?
The speed and performance of a website and a web page matter significantly when it comes to its SEO. A faster website is likely to rank higher on the search engine results page. It is also likely to get more web traffic and views. For business websites, this directly translates to increased turnover and better reach. The speed of a website is consi
6 min read
What is rendering prop pattern in React Native ?
React Native is a javascript-based language that is used for designing UI (User Interface). In this article, we will learn about rendering prop patterns in React Native. The Render Props is a technique in ReactJS for sharing code between React components using a prop whose value is a function. The child component takes render props as a function an
3 min read
React.js Blueprint Popover2 Portal rendering
Blueprint is a React-based UI toolkit for the web. This library is very optimized and popular for building interfaces that are complex and data-dense for desktop applications. In this article, we'll discuss React.js Blueprint Popover2 Portal rendering. Popovers help in displaying the floating content next to the target element. With the help of por
6 min read
What is Server-Side Rendering in React?
Server-Side Rendering (SSR) in React is a technique that involves rendering React components on the server side instead of the client side (browser). Traditionally, React applications are rendered on the client side, meaning that the browser downloads the JavaScript bundle, executes it, and renders the UI. In contrast, with SSR, the server pre-rend
2 min read
How to implement Conditional Rendering in React?
This article explores JavaScript's conditional rendering in React JS, including various methods, syntax, and applications, leveraging React's virtual DOM, reusable components, props, and rapid rendering capabilities in single-page UI applications. We will use the following approaches to implement conditional rendering in React Table of Content if-e
4 min read
Server-Side Rendering (SSR) with React Hooks
Server-side rendering (SSR) is a technique used to render web pages on the server side and send the fully rendered page to the client's browser. This approach offers benefits such as improved SEO and faster initial page loads. With the introduction of React Hooks, SSR implementation has become even more streamlined. In this article, we'll explore h
4 min read