mason
mason-log.

mason

mason.

안녕하세요. mason 입니다.

vue

Vue 라이프사이클.

mount, update, unmount 훅, onMounted, watch와의 관계

Vue 컴포넌트는 생성 → 마운트 → 업데이트 → 언마운트 단계를 거치며, Composition API에서는 onMounted 같은 훅 함수로 각 시점에 로직을 붙입니다.

🪝 Composition API 훅

Vue 라이프사이클 mount update unmount

시점
onBeforeMountDOM mount 직전
onMountedDOM mount 완료
onBeforeUpdatereactive 데이터 변경, DOM patch 직전
onUpdatedDOM patch 완료
onBeforeUnmount제거 직전
onUnmounted제거 완료
import { onMounted, onUnmounted } from 'vue';

onMounted(() => {
  window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
});

⚖️ React와 비교

VueReact (대략)
onMounteduseEffect(() => {}, [])
onUpdateduseEffect (deps 변경 후)
onUnmounteduseEffect cleanup
  • Vue는 단계별 훅이 명시적

  • React는 effect 하나에 mount/update/cleanup을 합쳐 쓰는 경우가 많음

  • DOM 측정, 외부 라이브러리 init → onMounted

  • 타이머, subscription → onUnmounted에서 해제

  • watch특정 ref/reactive 변경에 반응, lifecycle은 컴포넌트 단계에 반응

🔗 참고 자료