[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
@@ -2,139 +2,202 @@
id: wiki-2026-0508-virtual-dom과-reconciliation
title: Virtual DOM과 Reconciliation
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: []
aliases: [VDOM, React Fiber, Virtual DOM]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [auto-consolidated, technical-documentation]
confidence_score: 0.93
verification_status: applied
tags: [react, frontend, rendering, vdom, fiber, signals]
raw_sources: []
last_reinforced: 2026-05-08
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
language: typescript
framework: React-19
---
# [[Virtual DOM과 Reconciliation|Virtual DOM과 Reconciliation]]
# Virtual DOM과 Reconciliation
## 📌 한 줄 통찰 (The Karpathy Summary)
[[Virtual DOM|Virtual DOM]]은 UI의 이상적인 가상 표현을 메모리에 유지하는 프로그래밍 개념입니다 [1]. [[Reconciliation|Reconciliation]](재조정)은 이 Virtual DOM을 실제 DOM과 동기화하여 변경된 부분만 파악하고 효율적으로 업데이트하는 React의 핵심 프로세스입니다 [1, 2]. React는 O(n) 복잡도를 가진 휴리스틱 Diffing 알고리즘을 사용하여 실제 DOM 조작으로 인해 발생하는 비싼 렌더링 비용과 성능 저하를 최소화합니다 [3-5].
## 한 줄
> **"매 UI 의 in-memory tree (VDOM) 의 매 diff → 매 minimal real-DOM mutation 만 commit."** React 가 2013년 도입 → 2017년 Fiber rewrite → 2024년 React 19 (compiler) 로 evolve. 매 2026 은 매 fine-grained reactivity (SolidJS, Svelte 5 runes) 와 매 architectural rivalry — 매 VDOM 의 default 지위 의 erosion.
---
## 매 핵심
가상 DOM(Virtual DOM)은 메모리 상에 사용자 인터페이스(UI) 요소들을 일반 자바스크립트 객체 형태로 가볍게 표현한 개념입니다 [1, 2]. 재조정(Reconciliation)은 React가 변경 사항을 감지하기 위해 새로 생성된 가상 DOM과 이전 버전의 가상 DOM을 비교(diff)하여, 실제 DOM을 가장 효율적인 방식으로 업데이트하는 프로세스를 의미합니다 [1-3]. 이 방식을 통해 개발자는 선언적 API를 사용하여 UI의 상태만 정의하면 되며, 수동적인 DOM 조작과 이로 인해 발생하는 렌더링 비효율성을 신경 쓰지 않아도 됩니다 [1, 3, 4].
### 매 VDOM 작동
1. **Render**: JSX → VDOM tree (object literal).
2. **Diff (reconcile)**: prev tree vs next tree 의 비교 — 매 O(n) heuristic.
3. **Commit**: minimal real-DOM operation 의 batch apply.
## 📖 구조화된 지식 (Synthesized Content)
**Virtual DOM의 개념과 도입 배경**
* 브라우저의 실제 DOM을 직접 수정하는 작업은 레이아웃(Reflow)과 페인트(Repaint) 단계를 반복적으로 트리거하기 때문에 본질적으로 매우 느립니다 [2].
* React는 이 문제를 추상화하기 위해 가볍고 메모리 내에 존재하는 UI 표현인 Virtual DOM을 도입했습니다 [2].
* 이를 통해 개발자는 원하는 UI 상태를 선언적으로 명시하기만 하면 되며, React의 ReactDOM과 같은 라이브러리가 내부적으로 속성 조작, 이벤트 처리 및 수동 DOM 업데이트를 알아서 관리하게 됩니다 [1, 2].
* React 세계에서 Virtual DOM은 일반적으로 사용자 인터페이스를 나타내는 객체인 'React Elements'를 의미하며, 컴포넌트 트리에 대한 추가 정보를 담고 있는 내부 객체인 'Fiber' 역시 그 구현의 일부로 간주될 수 있습니다 [6].
### 매 React Fiber (2017+)
- **Unit of work**: 매 fiber node — 매 component 의 단위.
- **Interruptible**: 매 work loop 가 매 yield 가능 — 매 priority-based scheduling.
- **Double buffering**: current tree + work-in-progress tree.
- **Lanes (2020)**: priority bitmask — sync, transition, idle.
**Reconciliation과 휴리스틱 Diffing 알고리즘**
* 상태([[State|State]])나 속성(Props)이 업데이트되면 `render()` 함수는 새로운 React Element 트리를 반환하며, React는 이를 가장 최근의 트리와 비교하여 UI를 어떻게 효율적으로 업데이트할지 계산합니다 [4].
* 두 트리를 비교하여 변환하기 위한 최소한의 연산을 찾는 일반적인 알고리즘은 O(n^3)의 복잡도를 가지므로 실제 애플리케이션에 적용하기에는 비용이 너무 높습니다 [4].
* 따라서 React는 다음 두 가지 가정에 기반한 **O(n) 휴리스틱 알고리즘**을 구현했습니다 [3-5]:
1. 서로 다른 타입의 요소(Elements)는 본질적으로 다른 트리를 생성한다 [3, 5].
2. 개발자가 `key` 속성을 제공하여 여러 렌더링 간에 어떤 자식 요소가 안정적인지 힌트를 줄 수 있다 [3, 5].
### 매 Reconciliation heuristic
- **Different element type → 매 unmount + remount**: `<div>``<span>` 매 subtree throw.
- **Same type → 매 props update**: attribute diff 만.
- **Key**: list 의 stable identity — 매 key 없으면 매 index-based, 매 잘못된 reuse.
**비교(Diffing) 프로세스 상세 처리**
* **다른 타입의 요소:** 루트 요소의 타입이 다르면(예: `<a>`에서 `<img>`로, 혹은 `<div>`에서 `<span>`으로 변경), React는 기존 트리를 완전히 파괴하고 처음부터 새 트리를 구축합니다 [3, 7]. 이 과정에서 이전 DOM 노드는 파괴되며 연관된 모든 컴포넌트의 상태(State)가 유실됩니다 [7].
* **같은 타입의 DOM 요소:** 동일한 타입의 React DOM 요소를 비교할 때는 기본 DOM 노드를 유지한 채, `className`이나 `style` 등 변경된 속성(Attributes)만을 업데이트합니다 [8, 9].
* **같은 타입의 컴포넌트 요소:** 컴포넌트가 업데이트될 때 인스턴스는 동일하게 유지되어 렌더링 간에 상태가 보존됩니다. React는 새 요소와 일치하도록 기본 컴포넌트 인스턴스의 props를 업데이트하고 수명 주기(Lifecycle) 메서드를 호출한 뒤, 자식 노드에 대해 재귀적으로 처리합니다 [9, 10].
* **자식 노드 처리와 Key 속성:** 자식 노드를 순회할 때 리스트의 맨 앞에 요소를 추가하면 전체 트리가 변경된 것으로 인식해 매우 비효율적으로 작동할 수 있습니다 [10, 11]. 이를 해결하기 위해 `key` 속성을 사용하여 원본 트리와 후속 트리의 자식을 정확히 매칭시킵니다 [3, 11]. `key`는 형제 노드 사이에서 안정적이고 예측 가능하며 고유해야 성능 저하와 상태 유실을 방지할 수 있습니다 [12].
### 매 2026 alternatives
- **SolidJS signals**: 매 VDOM X — 매 fine-grained dependency tracking. 매 update 가 매 mutation site 직접.
- **Svelte 5 runes**: 매 compile-time reactivity — 매 runtime overhead 최소.
- **Vue 3.5 (Vapor mode)**: 매 VDOM-less compile target — opt-in.
- **React 19 compiler**: 매 manual memoization (useMemo, useCallback) 의 elimination — 매 VDOM 유지하되 매 cost 감소.
**[[React Fiber|React Fiber]] 아키텍처를 통한 렌더링 최적화**
* 과거 동기적인 스택 재조정자(Stack reconciler)는 대규모 애플리케이션 처리 시 메인 스레드를 차단([[Blocking|Blocking]])하여 UI의 반응성을 떨어뜨리는 문제가 있었습니다 [13, 14].
* React 16은 이를 해결하기 위해 동시성 렌더링([[Concurrent Rendering|Concurrent Rendering]])을 지원하는 **Fiber 아키텍처**로 재조정 엔진을 완전히 재작성했습니다 [15-17].
* Fiber는 렌더링 작업을 '작업 단위(Unit of work)'로 나누고, 우선순위(Lanes) 시스템을 통해 긴급한 상호작용(클릭, 타이핑 등)을 위해 작업을 일시 중단, 양보(Yield), 및 재개할 수 있도록 지원합니다 [14, 16, 18, 19]. 이로 인해 Virtual DOM의 재조정 과정 중에도 UI 반응성을 유지할 수 있습니다 [16, 18].
### 매 응용
1. **SPA**: React, Preact, Inferno — 매 VDOM 기반.
2. **Server components (RSC)**: 매 server 에서 render → 매 wire format → 매 client hydrate.
3. **Cross-platform**: React Native, Lynx — 매 VDOM 의 platform-agnostic 의 leverage.
---
## 💻 패턴
* **가상 DOM의 필요성과 역할**
실제 DOM을 직접 수정하는 작업은 브라우저의 레이아웃(Reflow) 및 페인트(Repaint) 단계를 매번 유발하기 때문에 본질적으로 느립니다 [1, 5]. React는 가상 DOM이라는 메모리 상의 이상적인 UI 표현을 유지하며, 이를 통해 선언된 상태와 실제 DOM이 일치하도록 최소한의 업데이트만 수행하여 렌더링을 최적화합니다 [1, 3]. 설계상 가상 DOM 트리는 불변(immutable) 객체로 취급됩니다 [6].
### 매 minimal VDOM (educational)
```typescript
type VNode = { type: string; props: Record<string, any>; children: (VNode | string)[] };
* **휴리스틱 Diff 알고리즘과 $O(n)$ 최적화**
두 개의 트리를 비교하여 최소한의 연산으로 변환하는 일반적인 알고리즘은 $O(n^3)$의 시간 복잡도를 가지므로, 요소가 많은 실제 애플리케이션에 적용하기에는 비용이 너무 큽니다 [7, 8]. 이에 React는 다음 두 가지 가정을 바탕으로 $O(n)$ 복잡도로 동작하는 휴리스틱 기반의 diff 알고리즘을 사용합니다 [7, 8].
1. **다른 타입의 요소**: 루트 요소의 타입이 다르면(예: `<a>`에서 `<img>`로 변경), React는 이전 트리를 완전히 파괴하고 새로운 트리를 처음부터 구축합니다 [7, 9]. 반면, 같은 타입의 DOM 요소인 경우에는 유지하면서 변경된 속성(예: className이나 특정 style)만 업데이트합니다 [10].
2. **Key 속성**: 여러 번의 렌더링 사이에서 리스트 내의 어떤 자식 요소가 안정적으로 유지되는지 식별하기 위해 `key` 속성을 사용합니다 [7, 8]. 자식 요소의 순서가 변경되거나 추가될 때 `key`를 활용하면 기존 하위 트리를 파괴하지 않고 요소의 이동만으로 트리를 효율적으로 재구성할 수 있습니다 [11, 12].
function h(type: string, props = {}, ...children: (VNode | string)[]): VNode {
return { type, props, children };
}
* **[[React Fiber|React Fiber]]와 점진적 재조정(Incremental Reconciliation)**
React 16부터는 기존의 동기식 차단(synchronous [[Blocking|Blocking]]) 문제를 해결하고 동시성 렌더링([[Concurrent Rendering|Concurrent Rendering]])을 지원하기 위해, 재조정 엔진을 완전히 재작성한 'Fiber 아키텍처'를 도입했습니다 [13-15]. Fiber 기반의 재조정 과정은 크게 두 단계로 나뉩니다.
1. **렌더 단계(Render phase)**: DOM을 조작하지 않는 순수한 연산 과정으로, 중단이나 취소, 재시작이 가능합니다. 이 단계에서는 Fiber 트리를 순회하며 이전 상태와 새로운 상태의 차이를 계산하고, 업데이트나 삽입 등 변화가 필요한 요소들의 효과 목록(effect list)을 구축합니다 [16].
2. **커밋 단계(Commit phase)**: 렌더 단계와 달리 동기적으로 작동하며 중단할 수 없습니다. 구축된 효과 목록을 바탕으로 모든 변경 사항과 실제 DOM 조작(삽입, 삭제, 속성 업데이트)을 한 번에 적용합니다 [17].
* **재조정 알고리즘의 트레이드오프**
재조정 알고리즘은 휴리스틱에 의존하기 때문에 주어진 가정이 충족되지 않으면 성능이 저하될 수 있습니다 [18]. 예를 들어, 하위 트리가 형제 요소 사이에서 이동한 것은 파악할 수 있지만, 트리 내의 완전히 다른 위치로 이동한 것은 인식하지 못해 전체 하위 트리를 다시 렌더링하게 됩니다 [19]. 또한 인덱스를 `key`로 사용하거나 예측 불가능한 불안정한 키를 사용할 경우, 불필요한 DOM 노드 및 컴포넌트 재생성으로 인해 성능 저하와 자식 컴포넌트의 상태 손실이 발생할 수 있습니다 [18, 20].
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
No trade-offs available.
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[React Fiber Architecture|React Fiber Architecture]], Critical Rendering Path (CRP), [[Concurrent Rendering|Concurrent Rendering]]
- **Projects/Contexts:** React Application Performance [[Optimization|Optimization]]
- **Contradictions/Notes:** 소스에 따르면 Virtual DOM 트리는 설계상 불변(immutable)으로 취급되지만, 단일 자식 노드를 여러 위치에서 사용하는 경우 복사 비용 문제가 발생할 수 있습니다. 이를 해결하기 위해 React는 현재 설치된 상태를 나타내는 가변적인 형태의 "Augmented DOM" 구조를 구축하며, 이것이 바로 React의 Fiber 데이터 구조가 수행하는 역할입니다 [20].
---
*Last updated: 2026-04-25*
---
- **Related Topics:** [[React Fiber 아키텍처|React Fiber 아키텍처]], 브라우저 렌더링 과정 (Critical Rendering Path), [[Reflow 및 Repaint|Reflow 및 Repaint]]
- **Projects/Contexts:** [[프론트엔드 기초 구조 이해 핵심 목적|프론트엔드 기초 구조 이해 핵심 목적]]
- **Contradictions/Notes:** 소스 자료에 따르면, 두 트리를 비교하는 완벽한 트리 변환 알고리즘은 이론적으로 $O(n^3)$의 복잡도를 요구하여 브라우저에서 실행하기 어렵습니다. 하지만 React는 '타입(Type)'과 '키(Key)'라는 두 가지 단순하고 강력한 가정만으로 알고리즘 복잡도를 $O(n)$으로 극적으로 줄임으로써 빠른 성능을 확보했습니다 [7, 8, 21].
---
*Last updated: 2026-04-25*
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
function diff(prev: VNode | null, next: VNode | null, parent: HTMLElement, index = 0) {
if (!prev) {
parent.appendChild(render(next!));
} else if (!next) {
parent.removeChild(parent.childNodes[index]);
} else if (prev.type !== next.type) {
parent.replaceChild(render(next), parent.childNodes[index]);
} else if (typeof next === "object") {
updateProps(parent.childNodes[index] as HTMLElement, prev.props, next.props);
const len = Math.max(prev.children.length, next.children.length);
for (let i = 0; i < len; i++) {
diff(prev.children[i] as VNode, next.children[i] as VNode,
parent.childNodes[index] as HTMLElement, i);
}
}
}
```
## 🤔 의사결정 기준 (Decision Criteria)
### 매 React Fiber priority (lanes)
```typescript
import { startTransition, useDeferredValue } from "react";
**선택 A를 써야 할 때:**
- *(TODO)*
function SearchBox() {
const [query, setQuery] = useState("");
const deferred = useDeferredValue(query); // 매 low-priority lane
**선택 B를 써야 할 때:**
- *(TODO)*
return (
<>
<input value={query} onChange={e => setQuery(e.target.value)} />
<ExpensiveResults query={deferred} />
</>
);
}
**기본값:**
> *(TODO)*
// 매 startTransition: 매 non-urgent state update
function tabSwitch(newTab: Tab) {
startTransition(() => setActiveTab(newTab));
}
```
## ❌ 안티패턴 (Anti-Patterns)
### 매 key 의 올바른 사용
```tsx
// 매 BAD: index key — 매 reorder 시 매 잘못된 reuse
{items.map((item, i) => <Row key={i} {...item} />)}
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
// 매 GOOD: stable id
{items.map(item => <Row key={item.id} {...item} />)}
// 매 reorder edge case: 매 form input state 의 보존 의 보장
```
### 매 SolidJS signal (no VDOM)
```tsx
import { createSignal, createMemo, For } from "solid-js";
function Counter() {
const [count, setCount] = createSignal(0);
const doubled = createMemo(() => count() * 2);
// 매 JSX 가 매 reactive primitive 로 compile
// 매 setCount 호출 시 매 doubled 만 update — 매 component re-render X
return <button onClick={() => setCount(c => c + 1)}>{doubled()}</button>;
}
```
### 매 React 19 compiler (auto-memo)
```tsx
// 매 React 19 compiler enabled — 매 useMemo / useCallback 불필요
function Parent({ items }: { items: Item[] }) {
const sorted = items.toSorted((a, b) => a.score - b.score);
// 매 compiler 가 매 dependency analysis → 매 auto-memo
return sorted.map(item => <Child key={item.id} item={item} />);
}
```
### 매 RSC (server component)
```tsx
// 매 server component — 매 zero JS shipped
async function ProductPage({ id }: { id: string }) {
const product = await db.product.findUnique({ where: { id } });
return (
<article>
<h1>{product.name}</h1>
<ClientCart product={product} /> {/* 매 client island */}
</article>
);
}
```
### 매 reconciliation profiling
```tsx
import { Profiler } from "react";
<Profiler id="App" onRender={(id, phase, actualDuration) => {
if (actualDuration > 16) {
console.warn(`매 slow render: ${id} took ${actualDuration}ms`);
}
}}>
<App />
</Profiler>
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| 매 large existing React codebase | 매 React 19 + compiler |
| 매 new SPA, performance-critical | 매 SolidJS or Svelte 5 |
| 매 SEO + dynamic | 매 Next.js 15 (RSC) or Remix |
| 매 enterprise, 매 ecosystem 우선 | 매 React (libraries · talent pool) |
| 매 Vue ecosystem 매 lock-in | 매 Vue 3.5 + Vapor mode |
**기본값**: 매 generic web app 매 React 19 + Vite or Next.js 15.
## 🔗 Graph
- 부모: [[Frontend Frameworks]] · [[DOM]] · [[Reconciliation]]
- 변형: [[React Fiber]] · [[Preact]] · [[Inferno]]
- 응용: [[Next.js]] · [[Remix]] · [[React Native]] · [[React Server Components]]
- Adjacent: [[SolidJS]] · [[Svelte]] · [[Signals]] · [[Vue Vapor]]
## 🤖 LLM 활용
**언제**: 매 React component 의 generation — 매 LLM 이 매 JSX + hooks 패턴 의 well-trained.
**언제 X**: 매 fiber 의 internal debugging — 매 LLM 의 stale knowledge 의 risk.
## ❌ 안티패턴
- **매 index as key**: 매 list reorder 시 매 wrong state.
- **매 inline object props**: 매 매 render 마다 매 new ref → 매 child memo 무효 (compiler 이전).
- **매 huge component tree**: 매 single render 가 매 thousands node — 매 split 안 함.
- **매 useMemo 남용 (React 19 이전)**: 매 미세 update 의 over-memo — 매 measure 없이 의 cargo cult.
- **매 setState in render**: 매 infinite loop.
## 🧪 검증 / 중복
- Verified (React docs 2026; "React Fiber Architecture" by Andrew Clark; SolidJS docs; Svelte 5 release notes).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Fiber, React 19 compiler, signals 비교 추가 |