Explain the component lifecycle hooks in Vue 3.
With the Composition API, lifecycle hooks are functions called inside setup (or <script setup>):
- setup itself runs first, before the component is created. There is no
beforeCreate/createdequivalent; just write the code in setup. onBeforeMount: before the first render is inserted into the DOM.onMounted: the DOM exists. Use it for DOM access, third-party widgets, measuring elements, and client-only work.onBeforeUpdate/onUpdated: around re-renders caused by reactive changes. Avoid changing state inonUpdated(it can loop).onBeforeUnmount/onUnmounted: clean up timers, listeners, subscriptions and widget instances.onErrorCaptured: catch errors from descendants (an error boundary).onActivated/onDeactivated: for components cached by<KeepAlive>.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.