”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 反应虚拟 DOM

反应虚拟 DOM

发布于2024-11-08
浏览:924

Introduction

Hi, Gleb Kotovsky is here!

Today I wanna talk about Virtual DOM, specifically - React Virtual DOM

So, the virtual DOM (Virtual Document Object Model) is a cool programming idea that keeps a "virtual" version of a user interface in memory. This version syncs up with the browser's DOM (Document Object Model) using a library.

You’ll find the virtual DOM is a big part of many JavaScript front-end frameworks, and it’s one of the reasons they’re so efficient. In this article, we're going to dive into how the virtual DOM works in React and why it’s important for the library.

What is the DOM?

When a webpage loads in a browser, it typically receives an HTML document from the server. The browser then builds a logical, tree-like structure from this HTML to render the requested page for the user. This structure is known as the DOM.

The Document Object Model (DOM) represents a logical tree that describes a document. Each branch of the tree ends in a node , which contains an object . Because the browser parses the document into this tree structure, there is a need for methods that allow for programmatic access to the tree, enabling modifications to the document's structure, style, or content. This necessity led to the development of the DOM API, which offers these methods for manipulating the nodes representing the elements in the tree.

React Virtual DOM

React's Virtual DOM Implementation

To optimize re-rendering in websites and applications, many JavaScript frameworks offer different strategies. However, React employs the concept of the virtual DOM.

The virtual DOM in React represents the user interface as a "virtual" tree structure, where each element is a node containing an object. This representation is maintained in memory and synchronized with the browser's DOM through React's React DOM library.

When React and many other famous frameworks uses Virtual DOM, Svelte meanwhile has no Virtual DOM. Svelte works directly with the DOM in the browser and modifies it as needed.

Here's a simple example to illustrate the Virtual DOM in a React component:

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  const increment = () => setCount(count   1);

  return (
    

Count: {count}

); }

In this example:

  • The component renders a counter and a button.
  • When the button is clicked, the state is updated, prompting React to create a new Virtual DOM tree.
  • The diffing algorithm checks what has changed (only the count) and updates the real DOM accordingly.

After the component is first rendered and the state is count: 0, the actual DOM will look like this:

Counter

Count: 0

How the Virtual DOM Works:

Here's a simple example to illustrate the Virtual DOM in a React component, starting with the component definition:

1. Component Definition

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  const increment = () => setCount(count   1);

  return (
    

Counter

Count: {count}

); }

2. Initial Render Process

2.1 Component Initialization

When the component is first rendered, React calls the Counter function.

2.2 State Initialization

useState(0) initializes the component's state to 0.

2.3 Creating the Virtual DOM

React generates a Virtual DOM tree using the component's returned JSX structure. This tree is a lightweight representation of the UI.

For the initial render, the Virtual DOM might look like this:

{
  "type": "div",
  "props": {
    "children": [
      { "type": "h1", "props": { "children": "Counter" } },
      { "type": "p", "props": { "children": "Count: 0" } },
      { "type": "button", "props": { "children": "Increment" } }
    ]
  }
}

2.4 Updating the Real DOM

React then takes this Virtual DOM and calculates what changes need to be made to the actual DOM. In this case, it creates the following HTML:

Counter

Count: 0

3. User Interaction

When a user clicks the "Increment" button, the following steps occur:

3.1 Event Handling

The button's onClick event triggers the increment function, calling setCount(count 1).

3.2 State Update

The component's state is updated, which causes React to know that it needs to re-render the component with the new state.

4. Re-render Process

4.1 Component Re-invocation

React calls the Counter function again due to the state change.

4.2 New Virtual DOM Creation

A new Virtual DOM tree is created reflecting the updated state:

{
  "type": "div",
  "props": {
    "children": [
      { "type": "h1", "props": { "children": "Counter" } },
      { "type": "p", "props": { "children": "Count: 1" } },
      { "type": "button", "props": { "children": "Increment" } }
    ]
  }
}

4.3 Diffing the Virtual DOM

React compares the new Virtual DOM with the previous Virtual DOM. It identifies what has changed—in this case, the text in the

tag has changed from "Count: 0" to "Count: 1".

4.4 Reconciliation

Only the parts of the real DOM that have changed are updated. In this case, React updates the real DOM to reflect the new count:

Counter

Count: 1

5. Performance Optimization

5.1 Batching Updates

If multiple state updates occur in rapid succession (e.g., multiple button clicks), React may batch these updates together for efficiency, minimizing the number of re-renders and DOM updates.

Common Problems with React Virtual DOM and How to Avoid Them

  1. Performance Bottlenecks
    • Issue: Excessive re-renders can occur even with the Virtual DOM.
    • Solution: Use React.memo to memoize functional components.
const MyComponent = React.memo(({ value }) => {
  console.log('Rendered: ', value);
  return 
{value}
; });

Legacy: Use shouldComponentUpdate in class components:

class MyClassComponent extends React.Component {
  shouldComponentUpdate(nextProps) {
    return nextProps.value !== this.props.value;
  }

  render() {
    return 
{this.props.value}
; } }
  1. Inefficient Key Management
    • Issue: Improper handling of keys in lists can lead to bugs.
    • Solution: Use unique and stable keys, not array indices.
   const items = ['Apple', 'Banana', 'Cherry'];
      return (
        
    {items.map(item => (
  • {item}
  • // Prefer unique values as keys ))}
);
  1. Overusing State and Updates
    • Issue: Too many state updates lead to performance issues.
    • Solution: Combine related states
const [state, setState] = useState({
  name: '',
  age: 0,
});

const updateAge = (newAge) => {
  setState(prevState => ({ ...prevState, age: newAge }));
};

  1. Using Inline Functions
    • Issue: Inline functions create new instances on every render.
    • Solution: Use useCallback to memoize functions.
const increment = useCallback(() => {
  setCount(c => c   1);
}, []); // Only recreate the function if dependencies change

  1. Deep Component Trees
    • Issue: Deeply nested components trigger multiple re-renders.
    • Solution: Use context.
const CountContext = React.createContext();

const ParentComponent = () => {
  const [count, setCount] = useState(0);

  return (
    
  );
};

const ChildComponent = () => {
  const { count, setCount } = useContext(CountContext);
  return 
setCount(count 1)}>Count: {count}
; };
  1. Excessive Re-renders Due to Parent Component Updates
    • Issue: Child components re-render when parents update.
    • Solution: Memoize child components.
const ChildComponent = React.memo(({ count }) => {
  return 
Count: {count}
; });
  1. Inefficient Rendering of Expensive Components
    • Issue: Expensive components can slow down the app.
    • Solution: Use React.lazy and React.Suspense.
const LazyComponent = React.lazy(() => import('./LazyComponent'));

const App = () => (
  Loading...}>
    
);

  1. Managing Side Effects
    • Issue: Side effects can cause bugs if not managed properly.
    • Solution: Use useEffect with proper dependencies.
useEffect(() => {
  const timer = setTimeout(() => {
    console.log('Time elapsed');
  }, 1000);

  return () => clearTimeout(timer); // Cleanup on unmount or if dependencies change
}, [dependencies]); // Replace with actual dependency

  1. Confusion Between State and Props
    • Issue: Misunderstanding when to use state vs. props.
    • Solution: Use props for externally managed data and state for local data.
const ParentComponent = () => {
  const [name, setName] = useState('John');

  return ;
};

const ChildComponent = ({ name, setName }) => (
  

{name}

);
  1. Neglecting Accessibility
    • Issue: Accessibility concerns can be ignored.
    • Solution: Use semantic HTML and accessibility tools.
const AccessibleButton = () => (
  
);

Conclusion

To wrap things up, React’s Virtual DOM is a fantastic feature that really boosts the performance of your web applications. By creating a lightweight version of the actual DOM, React can make updates more efficiently, avoiding the slowdowns that come with direct DOM manipulation.

That said, it’s important to watch out for common issues like excessive re-renders, poor key management in lists, and mixing up state and props. By keeping some best practices in mind—like using memoization, deploying context for handling state, and managing side effects wisely—you can get the most out of React and keep your apps running smoothly.

Happy hacking!

Resources

1) https://www.geeksforgeeks.org/reactjs-virtual-dom/
2) https://svelte.dev/blog/virtual-dom-is-pure-overhead
3) https://refine.dev/blog/react-virtual-dom/#introduction

版本声明 本文转载于:https://dev.to/gaundergod/react-virtual-dom-45al?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • 引用计数与跟踪垃圾收集
    引用计数与跟踪垃圾收集
    你好,Mentes Tech! 您知道内存释放上下文中的引用计数和引用跟踪是什么吗? 引用跟踪(或跟踪垃圾收集)和引用计数(引用计数)之间的区别在于每种技术用于识别和释放不存在的对象内存的方法。使用时间更长。 我将解释每一个,然后强调主要差异。 引用计数(引用计数) 工作原理:内存...
    编程 发布于2024-11-08
  • 单行SQL查询失败时如何返回默认值?
    单行SQL查询失败时如何返回默认值?
    单行查询失败时返回默认值在执行SQL查询获取特定数据时,经常会遇到没有对应行的情况存在。为了避免返回空结果,您可能需要提供默认值。考虑以下 SQL 语句,该语句检索流的下一个计划项目:SELECT `file` FROM `show`, `schedule` WHERE `channel` = 1...
    编程 发布于2024-11-08
  • Cypress 自动化可访问性测试:综合指南
    Cypress 自动化可访问性测试:综合指南
    介绍 辅助功能是 Web 开发的一个重要方面,确保所有用户(包括残障人士)都可以与您的 Web 应用程序有效交互。自动化可访问性测试有助于在开发过程的早期识别和解决可访问性问题。在这篇文章中,我们将探讨如何使用 Cypress 实现自动化可访问性测试,利用 cypress-axe ...
    编程 发布于2024-11-08
  • 为什么 Javascript 和 jQuery 找不到 HTML 元素?
    为什么 Javascript 和 jQuery 找不到 HTML 元素?
    Javascript 和 jQuery 无法检测 HTML 元素当尝试使用 Javascript 和 jQuery 操作 HTML 元素时,您可能会遇到令人沮丧的问题未定义的元素。当脚本尝试访问 HTML 文档中尚未定义的元素时,就会出现这种情况。在提供的 HTML 和脚本中,“script.js”...
    编程 发布于2024-11-08
  • Polars 与 Pandas Python 数据帧的新时代?
    Polars 与 Pandas Python 数据帧的新时代?
    北极熊与熊猫:有什么区别? 如果您一直关注 Python 的最新发展,您可能听说过 Polars,一个用于处理数据的新库。虽然 pandas 长期以来一直是首选库,但 Polars 正在掀起波澜,尤其是在处理大型数据集方面。那么,Polars 有什么大不了的呢?它和熊猫有什么不同?...
    编程 发布于2024-11-08
  • 使用 Golang 使用 Api 网关模式构建基本的微服务在线商店后端 - 第 1 部分
    使用 Golang 使用 Api 网关模式构建基本的微服务在线商店后端 - 第 1 部分
    Introduction Hey, fellow developers! ? Ever thought about building a microservices architecture but felt overwhelmed by where to start? Worry...
    编程 发布于2024-11-08
  • 如何高效地查找多个Python列表中的相交元素?
    如何高效地查找多个Python列表中的相交元素?
    识别多个Python列表中的共享元素在Python中,提取两个列表的交集可以使用set.intersection()函数来实现。然而,确定多个列表的交集变得更加复杂。这是一个有效识别多个列表之间共享元素的解决方案:答案中提供的公式 set.intersection(*map(set,d)) 提供了一...
    编程 发布于2024-11-08
  • Go 中如何高效地将 UTF-8 字符串转换为字节数组?
    Go 中如何高效地将 UTF-8 字符串转换为字节数组?
    将 UTF-8 字符串转换为字节数组解组 JSON 需要字节切片输入,而字符串在 Go 中存储为 UTF-8 。本文探讨了 UTF-8 字符串到字节数组的高效转换。直接转换Go 允许将字符串转换为字节切片,创建字符串字节的副本:s := "some text" b := []by...
    编程 发布于2024-11-08
  • 我可以在单个 MySQLi 语句中准备多个查询吗?
    我可以在单个 MySQLi 语句中准备多个查询吗?
    在单个 MySQLi 语句中准备多个查询不可能在单个 MySQLi 语句中准备多个查询。每个 mysqli_prepare() 调用只能准备一个查询。执行多个查询的替代方法如果您需要一次性执行多个查询,您可以创建并为每个查询执行单独的 mysqli_prepare() 语句。$stmtUser = ...
    编程 发布于2024-11-08
  • 在 Golang 中安全使用 Map:声明和初始化的差异
    在 Golang 中安全使用 Map:声明和初始化的差异
    介绍 本周,我正在为 golang 开发一个 API 包装器包,它处理发送带有 URL 编码值的 post 请求、设置 cookie 以及所有有趣的东西。但是,当我构建主体时,我使用 url.Value 类型来构建主体,并使用它来添加和设置键值对。然而,我在某些部分遇到了有线零指针...
    编程 发布于2024-11-08
  • 下一个目标
    下一个目标
    我刚刚完成了我的论文,并以令人印象深刻的分数9.1/10,我对此感到非常自豪。提交给 REV-ECIT 2024 的截止日期是 9 月 30 日,目的是将我的论文变成已发表的期刊文章。目前我正在博士生导师的支持下完善我的工作,非常感谢他的指导。 ? 另外,在与SA进行了很长时间的面试后,提出了一些...
    编程 发布于2024-11-08
  • Better - 人工智能驱动的代码审查器 GitHub Action
    Better - 人工智能驱动的代码审查器 GitHub Action
    代码审查对于维护标准和强调项目中代码的最佳实践始终至关重要。这不是一篇关于开发人员应该如何审查代码的文章,更多的是关于将一​​部分代码委托给 AI。 正如 Michael Lynch 在他的文章“如何像人类一样进行代码审查”中提到的那样——我们应该让计算机处理代码审查的无聊部分。虽然迈克尔强调格式化...
    编程 发布于2024-11-08
  • 如何使用 Java 8 有效地统计列表中的词频?
    如何使用 Java 8 有效地统计列表中的词频?
    使用 Java 8 计算词频在 Web 开发和数据分析中,理解词频至关重要。为了实现这一目标,我们将深入研究如何使用 Java 8 计算列表中单词的频率。Java 8 解决方案Java 8 中的 Stream API 为单词提供了一个优雅的解决方案频率计数。首先,创建一个单词列表:List<S...
    编程 发布于2024-11-08
  • 什么是封装以及如何使用它。
    什么是封装以及如何使用它。
    什么是封装? Java 中的封装就是隐藏某些东西如何工作的细节,同时仍然允许其他人使用它。您将数据(如变量)和方法(如函数)分组到一个单元中,称为类。您不是让每个人都直接访问您的数据,而是提供方法(getter 和 setter)来控制数据的访问或更改方式。这样,您可以保护您的数据并保持代码整洁和有...
    编程 发布于2024-11-08
  • Java 中的倒置二叉树
    Java 中的倒置二叉树
    最近,我开始练习一些 LeetCode 练习,以提高我的算法/数据结构技能。我可以说,该平台提供了一个良好的环境,可以与其他开发人员一起练习和学习多种编程语言的解决方案,与他人讨论、分享解决方案,并练习大公司要求的代码挑战。 什么是 LeetCode? LeetCode 是一个帮助候...
    编程 发布于2024-11-08

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3