🌐 Web Development

Virtual DOM

Virtual DOM

An in-memory representation of the DOM. Applies only the changes to the real DOM. Core to React.

📖 Detailed Explanation

A Virtual DOM is a lightweight JavaScript object representation of the actual DOM. When a UI change is needed, the Virtual DOM is updated first, compared with the previous Virtual DOM (diffing), and only the changed parts are applied to the actual DOM (reconciliation).

Manipulating the actual DOM is expensive. When the DOM is changed, the browser performs layout recalculation, repaint, and reflow, and frequent DOM manipulation causes performance degradation. The Virtual DOM minimizes the number of DOM manipulations by batching changes.

React popularized the Virtual DOM concept in 2013. When a component is rendered, React creates a Virtual DOM tree, compares it with the previous tree, and reflects only the differences in the actual DOM. This process is called Reconciliation, and from React 18 onward it is handled more efficiently with the Fiber architecture.

The Virtual DOM is not always fast. For simple changes, it can actually become overhead. Svelte generates optimized code at compile time without a Virtual DOM, and Solid.js performs precise DOM updates without a Virtual DOM through fine-grained reactivity. It is good to understand these differences when choosing a framework.

💻 Code Example

// Virtual DOM 개념 이해를 위한 간단한 구현

// 1. Virtual DOM 노드 생성 함수
function createElement(type, props, ...children) {
  return {
    type,
    props: props || {},
    children: children.flat()
  };
}

// 2. Virtual DOM → 실제 DOM 변환
function render(vNode) {
  if (typeof vNode === 'string' || typeof vNode === 'number') {
    return document.createTextNode(vNode);
  }

  const element = document.createElement(vNode.type);

  // props 적용
  Object.entries(vNode.props).forEach(([key, value]) => {
    if (key.startsWith('on')) {
      element.addEventListener(key.slice(2).toLowerCase(), value);
    } else {
      element.setAttribute(key, value);
    }
  });

  // 자식 렌더링
  vNode.children.forEach(child => {
    element.appendChild(render(child));
  });

  return element;
}

// 3. 사용 예시 (JSX 없이)
const vdom = createElement('div', { class: 'container' },
  createElement('h1', null, 'Hello Virtual DOM'),
  createElement('button', { onClick: () => alert('클릭!') }, '클릭하세요')
);

// 4. 실제 DOM에 마운트
document.body.appendChild(render(vdom));

// React에서의 실제 동작 방식
// JSX → createElement 호출 → Virtual DOM 생성 → Diffing → DOM 업데이트
// <div>Hello</div> 는 React.createElement('div', null, 'Hello')로 변환됨

🗣️ Say It Like This in Practice

💬 In an Interview
"The Virtual DOM is an in-memory representation of the DOM. When state changes, it creates a new Virtual DOM and compares it with the previous one. It applies only the changed parts to the actual DOM, which reduces unnecessary re-rendering. In React, the key prop identifies list items, which helps efficient diffing."
💬 In a Performance Optimization Discussion
"The Virtual DOM itself is not a performance guarantee. To reduce unnecessary re-rendering, you need to use React.memo, useMemo, and useCallback appropriately. Always provide a stable key for lists, and using the index as the key can cause performance degradation and bugs."
💬 In a framework selection discussion
"Svelte generates DOM update code at compile time without a Virtual DOM. It has no runtime overhead, so it is advantageous in bundle size and execution speed. On the other hand, compared with React's huge ecosystem, the options are limited."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
Misconception: Virtual DOM = always fast

The Virtual DOM is advantageous for batching large-scale updates, but for simple changes it is actually overhead. Svelte and Solid.js use different approaches to avoid this.

❌
Using the array index as the key in a list

If you use the index as the key, when the order of list items changes, React matches them incorrectly, causing bugs and performance degradation. Use a unique id as the key.

✅
Correct optimization strategy

Reduce the re-rendering scope by splitting components, find bottlenecks with the React DevTools Profiler, and then apply memoization. Optimization without measurement is wasteful.

🔗 Related Terms

📚 Learn More