Vue KeepAlive의 기술적 구현과 Virtual DOM 캐싱 메커니즘

· frontend

서론

최근 프로젝트에서 Vue의 KeepAlive 컴포넌트를 최적화하면서 computed 속성을 활용한 동적 캐싱을 구현한 경험이 있습니다. 이 과정에서 KeepAlive가 실제 DOM이 아닌 Virtual DOM을 캐싱한다는 중요한 사실을 발견했고, 이를 바닐라 JavaScript로도 구현할 수 있다는 점이 흥미로웠습니다. 이번 글에서는 KeepAlive의 내부 동작 원리와 실제 구현 방법에 대해 기술적으로 깊이 있게 탐구해보겠습니다.

KeepAlive란 무엇인가?

Vue의 KeepAlive는 동적 컴포넌트나 조건부 렌더링에서 컴포넌트의 상태를 보존하는 내장 컴포넌트입니다. 일반적으로 컴포넌트가 언마운트될 때 모든 상태가 손실되지만, KeepAlive를 사용하면 컴포넌트의 인스턴스를 메모리에 유지하여 다시 마운트될 때 이전 상태를 복원할 수 있습니다.

<template>
  <KeepAlive :include="cachedComponents">
    <component :is="currentComponent" />
  </KeepAlive>
</template>

<script setup>
import { ref, computed } from "vue";

const currentComponent = ref("ComponentA");

// computed를 활용한 동적 캐싱 최적화
const cachedComponents = computed(() => {
  const shouldCache = ["ComponentA", "ComponentB"];
  return shouldCache.filter((name) => shouldCacheComponent(name));
});

function shouldCacheComponent(name) {
  // 복잡한 캐싱 로직 구현
  return true;
}
</script>

Vue KeepAlive의 내부 동작: Virtual DOM 캐싱

많은 개발자들이 오해하는 부분이 바로 여기입니다. KeepAlive는 실제 DOM 요소를 캐싱하는 것이 아니라 Virtual DOM을 캐싱합니다. 이는 성능과 메모리 효율성 측면에서 매우 중요한 차이점입니다.

Virtual DOM 캐싱 프로세스

// Vue 3의 KeepAlive 내부 구현 (단순화)
class KeepAliveImpl {
  constructor() {
    this.cache = new Map();
    this.keys = new Set();
  }

  // Virtual DOM 노드를 캐싱
  cacheVNode(vnode, key) {
    this.cache.set(key, {
      vnode: vnode,
      component: vnode.component,
      // 컴포넌트 인스턴스의 상태 보존
      state: vnode.component?.setupState,
    });
    this.keys.add(key);
  }

  // 캐시된 VNode 복원
  restoreVNode(key) {
    const cached = this.cache.get(key);
    if (cached) {
      // Virtual DOM과 컴포넌트 상태 복원
      return cached.vnode;
    }
    return null;
  }

  // 캐시 정리
  pruneCacheEntry(key) {
    const cached = this.cache.get(key);
    if (cached) {
      // 컴포넌트 언마운트 처리
      cached.component?.scope.stop();
      this.cache.delete(key);
      this.keys.delete(key);
    }
  }
}

실제 DOM과 Virtual DOM의 차이점

// 실제 DOM 캐싱 (비효율적)
const domCache = new Map();

function cacheDOM(element, key) {
  // DOM 요소 직접 캐싱 - 메모리 누수 위험
  domCache.set(key, element.cloneNode(true));
}

// Virtual DOM 캐싱 (Vue 방식)
const vnodeCache = new Map();

function cacheVNode(vnode, key) {
  // Virtual DOM 객체 캐싱 - 가벼움
  vnodeCache.set(key, {
    type: vnode.type,
    props: vnode.props,
    children: vnode.children,
    component: vnode.component,
  });
}

바닐라 JavaScript로 KeepAlive 구현하기

Vue의 KeepAlive 원리를 이해했으니, 이제 바닐라 JavaScript로 유사한 기능을 구현해보겠습니다.

기본 KeepAlive 클래스 구현

class VanillaKeepAlive {
  constructor(container) {
    this.container = container;
    this.cache = new Map();
    this.currentKey = null;
  }

  // 컴포넌트 정의
  defineComponent(key, factory) {
    if (!this.cache.has(key)) {
      this.cache.set(key, {
        factory: factory,
        instance: null,
        element: null,
        state: new Map(),
      });
    }
  }

  // 컴포넌트 활성화
  async activate(key) {
    if (this.currentKey === key) return;

    // 이전 컴포넌트 비활성화
    if (this.currentKey) {
      await this.deactivate(this.currentKey);
    }

    const cached = this.cache.get(key);
    if (!cached) {
      throw new Error(`Component ${key} not defined`);
    }

    // 캐시된 인스턴스가 있으면 복원, 없으면 새로 생성
    if (cached.instance) {
      this.restoreComponent(cached);
    } else {
      await this.createComponent(cached);
    }

    this.currentKey = key;
  }

  // 새 컴포넌트 인스턴스 생성
  async createComponent(cached) {
    const instance = await cached.factory();
    cached.instance = instance;
    cached.element = instance.render();

    // 상태 초기화 콜백
    if (instance.onActivated) {
      instance.onActivated();
    }

    this.container.appendChild(cached.element);
  }

  // 캐시된 컴포넌트 복원
  restoreComponent(cached) {
    // DOM 요소 다시 추가
    this.container.appendChild(cached.element);

    // 상태 복원
    if (cached.instance.setState && cached.state.size > 0) {
      for (const [key, value] of cached.state) {
        cached.instance.setState(key, value);
      }
    }

    // 활성화 콜백
    if (cached.instance.onActivated) {
      cached.instance.onActivated();
    }
  }

  // 컴포넌트 비활성화 (상태 보존)
  async deactivate(key) {
    const cached = this.cache.get(key);
    if (!cached || !cached.instance) return;

    // 현재 상태 저장
    if (cached.instance.getState) {
      const state = cached.instance.getState();
      cached.state.clear();
      for (const [stateKey, value] of Object.entries(state)) {
        cached.state.set(stateKey, value);
      }
    }

    // 비활성화 콜백
    if (cached.instance.onDeactivated) {
      cached.instance.onDeactivated();
    }

    // DOM에서 제거 (메모리에는 보존)
    if (cached.element && cached.element.parentNode) {
      cached.element.parentNode.removeChild(cached.element);
    }
  }

  // 캐시에서 완전 제거
  destroy(key) {
    const cached = this.cache.get(key);
    if (!cached) return;

    if (cached.instance && cached.instance.onDestroyed) {
      cached.instance.onDestroyed();
    }

    if (cached.element && cached.element.parentNode) {
      cached.element.parentNode.removeChild(cached.element);
    }

    this.cache.delete(key);
  }
}

실제 사용 예제

// 컴포넌트 팩토리 함수
async function createUserProfile() {
  return {
    state: {
      userId: null,
      userData: null,
      scrollPosition: 0,
    },

    render() {
      const element = document.createElement("div");
      element.innerHTML = `
        <div class="user-profile">
          <h2>사용자 프로필</h2>
          <div class="content" id="profile-content">
            <!-- 프로필 내용 -->
          </div>
        </div>
      `;
      return element;
    },

    getState() {
      return {
        ...this.state,
        scrollPosition:
          document.querySelector("#profile-content")?.scrollTop || 0,
      };
    },

    setState(key, value) {
      this.state[key] = value;
      if (key === "scrollPosition") {
        const content = document.querySelector("#profile-content");
        if (content) content.scrollTop = value;
      }
    },

    onActivated() {
      console.log("UserProfile 활성화됨");
      // 스크롤 위치 복원 등
    },

    onDeactivated() {
      console.log("UserProfile 비활성화됨");
    },
  };
}

// KeepAlive 사용
const container = document.getElementById("app");
const keepAlive = new VanillaKeepAlive(container);

keepAlive.defineComponent("userProfile", createUserProfile);
keepAlive.defineComponent("dashboard", createDashboard);

// 컴포넌트 전환
await keepAlive.activate("userProfile");
// 사용자가 다른 페이지로 이동
await keepAlive.activate("dashboard");
// 다시 프로필로 돌아가면 이전 상태가 보존됨
await keepAlive.activate("userProfile");

성능 고려사항과 최적화

메모리 관리

class OptimizedKeepAlive extends VanillaKeepAlive {
  constructor(container, options = {}) {
    super(container);
    this.maxCacheSize = options.maxCacheSize || 10;
    this.cacheTimeout = options.cacheTimeout || 5 * 60 * 1000; // 5분
    this.accessTimes = new Map();
  }

  // LRU 캐시 구현
  activate(key) {
    this.accessTimes.set(key, Date.now());

    // 캐시 크기 제한
    if (this.cache.size > this.maxCacheSize) {
      this.evictLeastRecentlyUsed();
    }

    return super.activate(key);
  }

  evictLeastRecentlyUsed() {
    let oldestKey = null;
    let oldestTime = Infinity;

    for (const [key, time] of this.accessTimes) {
      if (time < oldestTime) {
        oldestTime = time;
        oldestKey = key;
      }
    }

    if (oldestKey) {
      this.destroy(oldestKey);
      this.accessTimes.delete(oldestKey);
    }
  }

  // 만료된 캐시 정리
  cleanupExpiredCache() {
    const now = Date.now();
    for (const [key, time] of this.accessTimes) {
      if (now - time > this.cacheTimeout) {
        this.destroy(key);
        this.accessTimes.delete(key);
      }
    }
  }
}

조건부 캐싱 (Computed 스타일)

class ConditionalKeepAlive extends OptimizedKeepAlive {
  constructor(container, options = {}) {
    super(container, options);
    this.includePattern = options.include || /.*/;
    this.excludePattern = options.exclude || null;
  }

  shouldCache(key) {
    // include 패턴 확인
    if (!this.includePattern.test(key)) {
      return false;
    }

    // exclude 패턴 확인
    if (this.excludePattern && this.excludePattern.test(key)) {
      return false;
    }

    return true;
  }

  async activate(key) {
    if (!this.shouldCache(key)) {
      // 캐싱하지 않는 컴포넌트는 매번 새로 생성
      await this.createTemporaryComponent(key);
      return;
    }

    return super.activate(key);
  }

  async createTemporaryComponent(key) {
    const cached = this.cache.get(key);
    if (!cached) return;

    const instance = await cached.factory();
    const element = instance.render();

    // 이전 요소 제거
    this.container.innerHTML = "";
    this.container.appendChild(element);

    // 임시 컴포넌트이므로 캐시하지 않음
  }
}

실제 적용 사례와 패턴

Vue 스타일의 동적 캐싱

// Vue computed 스타일의 동적 캐싱 로직
class DynamicKeepAlive extends ConditionalKeepAlive {
  constructor(container, options = {}) {
    super(container, options);
    this.computedInclude = options.computedInclude || (() => []);
  }

  shouldCache(key) {
    // computed 함수 실행하여 동적으로 캐싱 대상 결정
    const includedKeys = this.computedInclude();

    if (Array.isArray(includedKeys)) {
      return includedKeys.includes(key);
    }

    if (includedKeys instanceof RegExp) {
      return includedKeys.test(key);
    }

    return super.shouldCache(key);
  }
}

// 사용 예제
const dynamicKeepAlive = new DynamicKeepAlive(container, {
  computedInclude: () => {
    // 사용자 권한이나 상태에 따라 동적으로 결정
    const userRole = getCurrentUserRole();
    const heavyComponents = ["dataVisualization", "reportDashboard"];

    return userRole === "premium" ? heavyComponents : [];
  },
});

성능 벤치마크와 비교

메모리 사용량 비교

// 성능 측정 유틸리티
class PerformanceMonitor {
  static measureMemoryUsage() {
    if (performance.memory) {
      return {
        used: performance.memory.usedJSHeapSize,
        total: performance.memory.totalJSHeapSize,
        limit: performance.memory.jsHeapSizeLimit,
      };
    }
    return null;
  }

  static async benchmarkKeepAlive(keepAlive, componentKeys) {
    const results = {
      activationTimes: [],
      memoryUsage: [],
      cacheHitRatio: 0,
    };

    let cacheHits = 0;
    const startMemory = this.measureMemoryUsage();

    for (let i = 0; i < 100; i++) {
      const key = componentKeys[i % componentKeys.length];

      const startTime = performance.now();
      const wasHit =
        keepAlive.cache.has(key) && keepAlive.cache.get(key).instance;

      await keepAlive.activate(key);

      const endTime = performance.now();
      results.activationTimes.push(endTime - startTime);

      if (wasHit) cacheHits++;

      if (i % 10 === 0) {
        results.memoryUsage.push(this.measureMemoryUsage());
      }
    }

    results.cacheHitRatio = cacheHits / 100;
    const endMemory = this.measureMemoryUsage();

    console.log("벤치마크 결과:", {
      평균_활성화_시간:
        results.activationTimes.reduce((a, b) => a + b) /
        results.activationTimes.length,
      캐시_히트_비율: results.cacheHitRatio,
      메모리_증가량: endMemory.used - startMemory.used,
    });

    return results;
  }
}

모범 사례와 주의사항

1. 메모리 누수 방지

class SafeKeepAlive extends DynamicKeepAlive {
  constructor(container, options = {}) {
    super(container, options);

    // 페이지 언로드 시 정리
    window.addEventListener("beforeunload", () => {
      this.cleanup();
    });
  }

  cleanup() {
    // 모든 이벤트 리스너 제거
    for (const [key, cached] of this.cache) {
      if (cached.instance && cached.instance.cleanup) {
        cached.instance.cleanup();
      }
    }

    this.cache.clear();
    this.accessTimes.clear();
  }

  destroy(key) {
    const cached = this.cache.get(key);
    if (cached && cached.instance) {
      // 이벤트 리스너 및 타이머 정리
      if (cached.instance.cleanup) {
        cached.instance.cleanup();
      }
    }

    super.destroy(key);
  }
}

2. 비동기 처리와 상태 동기화

class AsyncSafeKeepAlive extends SafeKeepAlive {
  constructor(container, options = {}) {
    super(container, options);
    this.pendingActivations = new Map();
  }

  async activate(key) {
    // 동일한 컴포넌트의 중복 활성화 방지
    if (this.pendingActivations.has(key)) {
      return this.pendingActivations.get(key);
    }

    const activationPromise = this._doActivate(key);
    this.pendingActivations.set(key, activationPromise);

    try {
      await activationPromise;
    } finally {
      this.pendingActivations.delete(key);
    }
  }

  async _doActivate(key) {
    // 실제 활성화 로직
    return super.activate(key);
  }
}

결론

Vue의 KeepAlive는 Virtual DOM 캐싱이라는 영리한 방식으로 컴포넌트 상태를 보존합니다. 이는 실제 DOM 조작 비용을 줄이면서도 메모리 효율성을 유지하는 균형잡힌 접근방식입니다.

바닐라 JavaScript로 구현해본 결과, KeepAlive의 핵심 원리는:

  1. Virtual DOM 캐싱: 실제 DOM이 아닌 가벼운 객체 구조 보존
  2. 상태 관리: 컴포넌트의 내부 상태와 UI 상태 분리 저장
  3. 생명주기 관리: 활성화/비활성화 시점의 적절한 콜백 처리
  4. 메모리 최적화: LRU 캐시와 조건부 캐싱을 통한 효율적 관리

특히 computed 속성을 활용한 동적 캐싱은 사용자 권한이나 애플리케이션 상태에 따라 캐싱 정책을 유연하게 조정할 수 있게 해줍니다. 이는 대규모 애플리케이션에서 메모리 사용량과 성능을 세밀하게 제어하는데 매우 유용합니다.

KeepAlive를 효과적으로 사용하기 위해서는 메모리 누수 방지, 적절한 캐시 크기 관리, 그리고 컴포넌트별 캐싱 필요성을 신중히 고려해야 합니다. 모든 컴포넌트를 캐싱하는 것이 항상 최선은 아니며, 사용자 경험과 성능 사이의 균형점을 찾는 것이 중요합니다.