What are Vue lifecycle hooks?
Why Interviewers Ask This
Interviewers use this question to quickly assess whether a candidate has the foundational knowledge required for Vue.js development. It reveals whether you understand the building blocks that more complex concepts rely on.
Answer
Vue lifecycle hooks let you execute code at specific stages of a component's life. Vue 3 hooks (Composition API): onBeforeMount — before the component is mounted (DOM not yet created); onMounted — component is mounted (DOM available, use for DOM access, fetch data, subscriptions); onBeforeUpdate — before the component re-renders due to state change; onUpdated — after re-render (DOM updated); onBeforeUnmount — before the component is unmounted (cleanup: clear timers, cancel subscriptions); onUnmounted — component is unmounted (DOM removed); onErrorCaptured — catches errors from descendant components; onActivated / onDeactivated — when a component inside <KeepAlive> is activated/deactivated. Usage in script setup: import { onMounted, onUnmounted } from "vue"; onMounted(() => { document.addEventListener("click", handler); }); onUnmounted(() => { document.removeEventListener("click", handler); });. Options API hooks: created (instance created, data/computed available, no DOM), mounted, updated, beforeDestroy → Vue 3 renamed to beforeUnmount, destroyed → unmounted. Setup() runs before beforeCreate and created — in Composition API, setup() replaces both. Most commonly used: onMounted (init, fetch data, DOM setup) and onUnmounted (cleanup).
Pro Tip
Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a Vue.js codebase.