Vue.js Developer interview question · Most asked
Describe the Vue component lifecycle hooks and what you use them for.
Summary
Composition API hooks: onBeforeMount, onMounted (DOM available; start DOM-dependent work), onBeforeUpdate / onUpdated, onBeforeUnmount / onUnmounted (clean up timers, listeners, subscriptions), plus onErrorCaptured, and onActivated / onDeactivated for KeepAlive. setup() itself replaces Vue 2's beforeCreate and created.
Longer Answer
Common patterns: fetch data in setup (or onMounted when it depends on the DOM, or with Suspense/Nuxt's data fetching for SSR); add global event listeners in onMounted and remove them in onUnmounted; avoid changing state in onUpdated, which can loop.
During server-side rendering only setup runs (plus onServerPrefetch); onMounted and later hooks run only in the browser, so browser-only code (window, localStorage) belongs there. Hooks must be registered synchronously during setup.
Key Points
- setup replaces beforeCreate/created.
- onMounted for DOM work; onUnmounted for cleanup.
- Only setup runs on the server.
- Register hooks synchronously.
More most-asked Vue.js Developer questions
- Options API or Composition API: what is the difference, and which would you use?
- How do you use Vue Router: dynamic routes, nested routes and navigation guards?
- How does Vue 3's reactivity system work, and how does it differ from Vue 2's?
- computed, watch or watchEffect: when do you use each?
- ref or reactive: what is the difference, and when do you use each?
- Why does v-for need a key, and why should it not be the index?
- How do props work, and what is one-way data flow?
- What are composables, and why did they replace mixins?