Home Web Front-end JS Tutorial How Many Resources Does a Click Consume? React vs. Vanilla

How Many Resources Does a Click Consume? React vs. Vanilla

Oct 22, 2024 am 06:24 AM

React, like any other JavaScript framework, handles a lot of things behind the scenes that we often don’t even think about.

And that’s okay—our job as developers is to solve problems, and the simpler the implementation, the better. You don’t always need to understand every detail of what a framework does for you.

JavaScript is an interesting language; it’s the king of the browser, and browsers are still used heavily, so I don’t see it disappearing anytime soon.

In fact, many native apps (iOS, Android, Smart TVs) run hybrid solutions using both native and web technologies.

In this post, I want to test a simple counter in React versus its Vanilla JavaScript version.

Measuring Performance with Chrome DevTools

First, let's talk about a useful tab that Chrome offers called Performance. This tab includes a recording feature that measures a web application's performance.

In this post, I'm going to focus on three key metrics: JS Heap, Nodes, and Listeners.

JS Heap: The heap is a region of memory in JavaScript where objects, arrays, and functions are stored. Unlike the stack, which holds primitive values (numbers, strings, booleans) and function calls, the heap manages dynamic memory allocation.

DOM Nodes: A DOM node is an individual element, attribute, or text within a web page's HTML, represented in the Document Object Model (DOM).

Event Listeners: In JavaScript, event listeners are functions that wait for specific events (e.g., clicks, key presses, mouse movements) on HTML elements. When the event occurs, the listener triggers, executing code in response.

Demo: Building a Basic React Counter

Alright, the UI is a simple counter. The UI is just a button with a click handler. Every time the button is clicked, the counter increments.

  • React Demo

The React code looks like this:

"use client";

import { useState } from "react";

export default function Page() {
  const [counter, setCounter] = useState(0);

  const incrementClickHandler = (event: { preventDefault: () => void }) => {
    event.preventDefault();

    setCounter((prevCounter) => prevCounter + 1);
  };

  return (
    <div style={{ maxWidth: 800, margin: "0 auto" }}>
      <a
        href="#"
        style={{
          display: "inline-block",
          padding: "20px 40px",
          fontSize: 28,
          border: "1px solid black",
          width: "100%",
          textAlign: "center",
          marginTop: 40,
        }}
        onClick={incrementClickHandler}
      >
        Increment {counter}
      </a>
    </div>
  );
}
Copy after login
Copy after login

The code is pretty self-explanatory. One thing to note is that the demo runs on top of Next.js, which is why we need "use client". Other than that, it's just a basic React component.

React Counter UI

How Many Resources Does a Click Consume? React vs. Vanilla

20 Seconds and Only One Click

Now, I'm going to open the Performance tab in Chrome, click the record icon, and let it run for 20 seconds while clicking the button only once. At the end of the 20 seconds, the performance results look like this:

How Many Resources Does a Click Consume? React vs. Vanilla

See how just one click bumps the numbers to:

React
JS Heap 3.4MB
Nodes 47
Listeners 287

?

20 Seconds with a Click per Second

Now, I’m going to let it run for another 20 seconds, but this time I’ll click the button once per second. Let’s take a look at the results:

How Many Resources Does a Click Consume? React vs. Vanilla

React
JS Heap 4MB
Nodes 46
Listeners 331

Two things to note about React:

a) When a state variable is updated, the component is re-rendered, meaning that in this case, the component was rendered 20 times.

b) Thanks to the virtual DOM, React only updates the nodes that need to be updated.

Now, let’s go back to the chart and see how the blue line (JS Heap) and the yellow line (Listeners) increment, while the green line (Nodes) remains constant.

It's also worth mentioning that the numbers didn't change much compared to the one-click run.

Demo: Building a Vanilla JavaScript Counter

Now, we have the same UI, but this time it’s built with vanilla HTML and JavaScript—no frameworks involved.

  • Vanilla Demo .
"use client";

import { useState } from "react";

export default function Page() {
  const [counter, setCounter] = useState(0);

  const incrementClickHandler = (event: { preventDefault: () => void }) => {
    event.preventDefault();

    setCounter((prevCounter) => prevCounter + 1);
  };

  return (
    <div style={{ maxWidth: 800, margin: "0 auto" }}>
      <a
        href="#"
        style={{
          display: "inline-block",
          padding: "20px 40px",
          fontSize: 28,
          border: "1px solid black",
          width: "100%",
          textAlign: "center",
          marginTop: 40,
        }}
        onClick={incrementClickHandler}
      >
        Increment {counter}
      </a>
    </div>
  );
}
Copy after login
Copy after login

One thing to mention is the necessity of the following element:

<html>
  <head>
    <script>
      let increment = 0;

      window.onload = function () {
        document.querySelector("#counter").innerText = increment;

        document.querySelector("a").addEventListener("click", function (event) {
          event.preventDefault();
          increment++;
          document.querySelector("#counter").innerText = increment;
        });
      };
    </script>
  </head>
  <body style="max-width: 800; margin: 0 auto; font-family: monospace;">
    <a
      href="#"
      style="
        display: inline-block;
        padding: 20px 40px;
        font-size: 28px;
        border: 1px solid black;
        width: 100%;
        text-align: center;
        text-decoration: none;
        color: black;
        margin-top: 40;
        box-sizing: border-box;
      "
      >Increment <span id="counter"></span>
    </a>
  </body>
</html>
Copy after login

that is manipulated with JavaScript to update its content:

<span id="counter"></span>
Copy after login

Vanilla Counter UI

How Many Resources Does a Click Consume? React vs. Vanilla

20 Seconds and Only One Click

Again, I’m going to click the record icon and let it run for 20 seconds, clicking the button only once.

Take a look at the results:

How Many Resources Does a Click Consume? React vs. Vanilla

Vanilla
JS Heap 1.7MB
Nodes 16
Listeners 20

20 Seconds with a Click per Second

Again, I’m going to click the record icon and let it run for another 20 seconds, but this time, I’ll click the button once per second. Check out the results:

How Many Resources Does a Click Consume? React vs. Vanilla

Vanilla
JS Heap 2.3MB
Nodes 42
Listeners 77

Just like in the React example, the blue line (JS Heap) and the yellow line (Listeners) increased over time. However, the green line (Nodes) is not constant; it increases as the button is clicked.

A Few Words on Garbage Collection

Garbage Collection: The main concept that garbage collection algorithms rely on is the concept of reference.

JavaScript automatically handles garbage collection for us; we don’t need to trigger it manually. In the previous examples, we saw how resources are consumed, but at some point, JavaScript takes care of releasing some of those resources through its garbage collector.

Conclusion

One click or twenty clicks isn’t that different in terms of resource consumption. As soon as a click happens, JavaScript allocates resources, and subsequent clicks continue to consume resources. However, the jump isn't as significant as the transition from zero to one click.

Let’s take a look at the end values for 20 clicks in both versions:

Vanilla React
JS Heap 2.3MB 4.0MB
Nodes 42 46
Listeners 77 331

It makes sense that React consumes more resources; that’s the cost of using a framework.

One key difference is that React attaches all the nodes from the beginning, while the vanilla version adds nodes as the clicks happen. However, in the end, both versions ended up with pretty much the same number of nodes.

The demo is quite simple, and at this level, there’s no significant difference in terms of performance. As mentioned earlier, there’s a price to pay for using the framework, but it’s worth it considering all the features and conveniences it provides.

The above is the detailed content of How Many Resources Does a Click Consume? React vs. Vanilla. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

See all articles