Tech Interview RoomStudy guides

Vue.js

Explain the component lifecycle hooks in Vue 3.

Intermediate · 2 min read · Lesson 6 of 12 in Vue.js

With the Composition API, lifecycle hooks are functions called inside setup (or <script setup>):

  1. setup itself runs first, before the component is created. There is no beforeCreate/created equivalent; just write the code in setup.
  2. onBeforeMount: before the first render is inserted into the DOM.
  3. onMounted: the DOM exists. Use it for DOM access, third-party widgets, measuring elements, and client-only work.
  4. onBeforeUpdate / onUpdated: around re-renders caused by reactive changes. Avoid changing state in onUpdated (it can loop).
  5. onBeforeUnmount / onUnmounted: clean up timers, listeners, subscriptions and widget instances.
  6. onErrorCaptured: catch errors from descendants (an error boundary).
  7. onActivated / onDeactivated: for components cached by <KeepAlive>.
  8. onServerPrefetch: SSR only, for fetching data on the server.

SSR note

Only setup and onServerPrefetch run on the server; onMounted and later never do, so put browser-only code (window, localStorage) there.

Mapping from React

onMounted + onUnmounted together are roughly useEffect(..., []) with a cleanup. Watching a prop is useEffect with that dependency.

Example

vue
<script setup>
import { onMounted, onBeforeUnmount, ref, useTemplateRef, markRaw } from 'vue';
import Chart from 'chart.js/auto';

const props = defineProps({ data: Object });
const canvas = useTemplateRef('canvas');           // Vue 3.5
const width = ref(window.innerWidth);
let chart;

function onResize() { width.value = window.innerWidth; }

onMounted(() => {
  chart = markRaw(new Chart(canvas.value, { type: 'bar', data: props.data }));
  window.addEventListener('resize', onResize);
});

onBeforeUnmount(() => {
  chart?.destroy();                                 // avoid leaks
  window.removeEventListener('resize', onResize);
});
</script>

<template>
  <canvas ref="canvas"></canvas>
  <p>Viewport: {{ width }}px</p>
</template>

Follow-up questions interviewers ask

Try answering each one before you open it.

What does KeepAlive do?

<KeepAlive> caches inactive component instances instead of destroying them, so switching tabs back preserves their state (form input, scroll position) and avoids refetching. include, exclude and max control what is cached (LRU). Use onActivated to refresh data when a cached component becomes visible again.