Skip to content
← All questions
Beginner

What are lifecycle hooks in Vue 3?

Composition APILifecycle

Lifecycle hooks let you run code at specific moments in a component's life: when it's created, mounted to the DOM, updated, or destroyed. In the Composition API, you register them as functions inside <script setup>.

The main hooks

ts
import {
  onBeforeMount,
  onMounted,
  onBeforeUpdate,
  onUpdated,
  onBeforeUnmount,
  onUnmounted
} from 'vue'

onBeforeMount(() => {
  // DOM not available yet
})

onMounted(() => {
  // DOM is ready, safe to access template refs, start timers, fetch data
})

onBeforeUpdate(() => {
  // reactive state changed, DOM not yet re-rendered
})

onUpdated(() => {
  // DOM re-rendered with new state
})

onBeforeUnmount(() => {
  // component still functional, clean up before removal
})

onUnmounted(() => {
  // component removed from DOM, all watchers stopped
})

Lifecycle flow

setup()

  ├── onBeforeMount
  ├── onMounted          ← DOM ready

  │   (reactive state changes)
  ├── onBeforeUpdate
  ├── onUpdated          ← DOM re-rendered

  │   (component removed)
  ├── onBeforeUnmount
  └── onUnmounted        ← fully cleaned up

Which hook for what

TaskHook
Fetch initial dataonMounted
Access template refsonMounted
Start a timer or listeneronMounted (clean up in onUnmounted)
React to DOM changes after updateonUpdated
Clean up timers, listeners, subscriptionsonUnmounted

Common pattern: setup + cleanup

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

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

Options API equivalent

If you see older code using Options API, the mapping is direct:

Composition APIOptions API
onBeforeMountbeforeMount
onMountedmounted
onBeforeUpdatebeforeUpdate
onUpdatedupdated
onBeforeUnmountbeforeUnmount
onUnmountedunmounted

There is no onCreated or onBeforeCreate in the Composition API. Code that would go there runs directly in setup() (or at the top level of <script setup>), since setup itself runs at creation time.

See also: What is the Composition API and how does it differ from the Options API? · Can you use await directly in script setup?

References

Released under the MIT License.