본문 바로가기

Front/향해플러스

Virtual DOM 만들기 - #4: renderElement (향해 플러스 2주차)

renderElement

`renderElement`는 가상 DOM을 실제 DOM에 렌더링하는 진입점이다. 최초 렌더링 시에는 `createElement`를 통해 DOM을 생성하고, 이후에는 diffing 알고리즘을 적용해 변경된 부분만 업데이트 한다.


1. normalizeVNode 로 정제

넘겨 받은 vNode가 아직 정제가 덜 된 상태일 수 있다. children의 중첩 배열 null, false 등의 값들을 normalizeVNode 을 실행해서 정제해준다.

const normalizedVNode = normalizeVNode(vNode);

2. 최초 렌더링 여부 판단

container에 _vNode가 없으면 최초 렌더링이다.

const oldNode = container._vNode;
const isFirstRender = !oldNode;

3. 최초 렌더링 시 createElement로 DOM 생성

if (isFirstRender) {
  container.appendChild(createElement(normalizedVNode));
} else {
  updateElement(container, normalizedVNode, oldNode);
}

최초 렌더링이면 DOM을 새로 만들고, 그렇지 않으면 `updateElement`로 diffing을 수행한다.

`updateElement` 는  다음 글에서 제작


4. 이벤트 리스너 등록

렌더링이 끝난 후 `setupEventListeners`로 이벤트 위임을 설정한다.

`setupEventListeners` 는 추후 eventManger 글에서 제작

setupEventListeners(container);


 

5. 현재 상태 저장

다음 렌더링 시 이전 상태와 비교할 수 있도록 container에 _vNode를 저장한다.

container._vNode = normalizedVNode;

 


전체 코드 예시

export function renderElement(vNode, container) {
  const normalizedVNode = normalizeVNode(vNode);
  const oldNode = container._vNode;
  const isFirstRender = !oldNode;

  if (isFirstRender) {
    container.appendChild(createElement(normalizedVNode));
  } else {
    updateElement(container, normalizedVNode, oldNode);
  }

  container._vNode = normalizedVNode;
  setupEventListeners(container);

  return container;
}

마무리

`renderElement`는 Virtual DOM과 실제 DOM을 연결하는 핵심 함수다. 이 구조를 구현하면 최초 렌더링과 재렌더링 모두 효율적으로 처리할 수 있다.

 

다음 글에서는 diffing 알고리즘의 핵심, `updateElement` 구현을 다뤄보자!