Lifecycle Hooks — Vue

Lifecycle hooks are functions Vue runs at given moments of a component's life: setup, onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount…

You write document.querySelector("h1") in a component's script, and get null. Yet the <h1> is right there in the template. The selector is fine. The timing isn't: the script runs before the template is placed on the page.

Every component has a life cycle: it's created, placed on the page, updated when its data changes, then removed from the page. In Vue's words, placing is called mounting, and removing is called unmounting. A lifecycle hook is a function you hand to Vue so it runs at one of those moments. Picture a day at Mrs. Sri's stall:

  1. In the morning, ingredients are prepared in the kitchen (setup).
  2. The rolling door opens, and the stall can be seen from the street (mounted). Only now can Mrs. Sri write the opening time on the menu board.
  3. All day, the menu board is updated whenever a dish sells out (updated).
  4. At night, before going home, the stove is turned off (unmounted).

In Vue, that day is the life of one component. Each lifecycle hook is like a task note you pin to one of those moments, such as "as soon as the rolling door opens, write the opening time".

onMounted: the component is on the page

This code runs as it is in the exercise editor:

console.log("setup ran")
console.log("h1 in setup:", document.querySelector("h1"))

onMounted(() => {
  console.log("Component loaded!")
  console.log("h1 in onMounted:", document.querySelector("h1").textContent)
})

---template---
<h1>Mrs. Sri's Stall</h1>

Console:

setup ran
h1 in setup: null
Component loaded!
h1 in onMounted: Mrs. Sri's Stall

document.querySelector("h1") finds the first <h1> on the whole page, and that <h1> may not belong to this component. To point at your component's own element, use a template ref. Give the element a ref attribute with a name, then get that element with useTemplateRef and the same name (Vue 3.5 and later):

import { useTemplateRef } from "vue"

const title = useTemplateRef("title")
console.log("ref in setup:", title.value)

onMounted(() => {
  console.log("ref in onMounted:", title.value.textContent)
})

---template---
<h1 ref="title">Mrs. Sri's Stall</h1>

Console:

ref in setup: null
ref in onMounted: Mrs. Sri's Stall

Like querySelector, a template ref is still null until the component is mounted, so read the template ref in onMounted. Before Vue 3.5, you wrote const title = ref(null), with a variable name exactly the same as the ref="title" attribute.

Filling in data as the component appears

Here onMounted fills the time ref with the time the component appeared:

const time = ref("")

onMounted(() => {
  time.value = "Loaded at: " + new Date().toLocaleTimeString()
})

---template---
<p id="time">{{ time }}</p>
When What <p id="time"> holds
first render empty
onMounted runs Loaded at: 10:15:30 AM

Hook order, parent and child

In the editor, onBeforeMount, onMounted, onBeforeUnmount and onUnmounted are provided. onBeforeMount runs just before the component is mounted. A child written as an object puts its script code, hooks included, inside a setup(props) function. Its props parameter holds the props from the parent, so props.name reads the name prop. In this code, each component prints its name and the name of the hook that is running:

console.log("App: setup")
onBeforeMount(() => console.log("App: onBeforeMount"))
onMounted(() => console.log("App: onMounted"))

const MenuCard = {
  props: ["name"],
  setup(props) {
    console.log(props.name + ": setup")
    onBeforeMount(() => console.log(props.name + ": onBeforeMount"))
    onMounted(() => console.log(props.name + ": onMounted"))
  },
  template: `<li>{{ name }}</li>`,
}

---template---
<ul>
  <component :is="MenuCard" name="Fried Rice" />
  <component :is="MenuCard" name="Iced Tea" />
</ul>

Console:

App: setup
App: onBeforeMount
Fried Rice: setup
Fried Rice: onBeforeMount
Iced Tea: setup
Iced Tea: onBeforeMount
Fried Rice: onMounted
Iced Tea: onMounted
App: onMounted

The parent starts first, but finishes last: both MenuCards are mounted before App: onMounted. App only counts as mounted once all its children are there.

There are four more hooks. When data changes, onBeforeUpdate runs before the view is updated, and onUpdated after it. When the component is removed, onBeforeUnmount runs before that, and onUnmounted after it. This table shows the order for the App above, if its menu list <ul> uses v-if or v-show:

Event Hooks that run, in order
App's data changes, its template re-renders onBeforeUpdate, then onUpdated
v-if removes the menu list App onBeforeUpdate, each MenuCard's onBeforeUnmount, then each onUnmounted, finally App onUpdated
v-show hides the menu list only App onBeforeUpdate and onUpdated; the MenuCards stay mounted

onUnmounted: cleaning up

onUnmounted runs when the component is removed from the DOM, for example because a v-if turns false or the user goes to another page. This is where you stop timers, event listeners and data subscriptions (connections that keep sending new data). In this example, onMounted starts a timer that adds 1 to seconds every second, and onUnmounted stops it:

const seconds = ref(0)
let timer

onMounted(() => {
  timer = setInterval(() => seconds.value++, 1000)
})

onUnmounted(() => {
  clearInterval(timer)
})

Without clearInterval, the timer keeps running every second even though the component is gone.

📌 onUpdated in the exercise editor

The editor doesn't provide onBeforeUpdate and onUpdated directly. If you call them, you get the error onUpdated is not defined. Take both from the Vue object on the script's first line: const { onBeforeUpdate, onUpdated } = Vue. In a .vue file, both are imported from "vue" like the other hooks.

⚠️ Hooks that run too early, too late, or never stop

TL;DR: Lifecycle hooks are functions Vue runs at given moments of a component's life: setup, onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted. onMounted runs after the component and all its children are in the DOM, so it's the place to read elements, fill in starting data or start a timer. The component's own elements are reached with a template ref (useTemplateRef), which is null before onMounted. Children finish mounting before their parent. onUnmounted runs when the component is removed, for example by v-if (but not by v-show). That's where timers are stopped. In a .vue file, hooks are imported from "vue". In the exercise editor, onBeforeMount, onMounted, onBeforeUnmount and onUnmounted are provided already.

⚡ onMounted: the component is on the page

Write:

console.log("setup ran")
console.log("h1 in setup:", document.querySelector("h1"))

onMounted(() => {
  console.log("Component loaded!")
  console.log("h1 in onMounted:", document.querySelector("h1").textContent)
})

---template---
<h1>Mrs. Sri's Stall</h1>
Guess first: the <h1> is right there in the template. What does the second line print?

h1 in setup: null. The component's script runs first, in the setup stage, while its elements aren't on the page yet.

Meaning: onMounted is a lifecycle hook: a function Vue runs at one moment of a component's life. onMounted runs its function after the component and all its children are placed in the DOM. Inside that function, the elements can be read: h1 in onMounted: Mrs. Sri's Stall.

⚡ The parent starts first, finishes last

Guess first: App has two MenuCard children. Each component prints its name in the console when its onMounted runs. Whose name is printed last?

App's. Both MenuCards are mounted first, then App: onMounted. App only counts as mounted once all its children are there.

Meaning: In each component, the order is setup, onBeforeMount (just before mounting), onMounted. When data changes, onBeforeUpdate runs before the view is updated, and then onUpdated after it.

⚡ onUnmounted: cleaning up

Write:

const seconds = ref(0)
let timer

onMounted(() => {
  timer = setInterval(() => seconds.value++, 1000)
})

onUnmounted(() => {
  clearInterval(timer)
})

Meaning: Here onMounted starts a timer, and onUnmounted stops it. onUnmounted runs when the component is removed from the DOM, for example because a v-if turns false. v-show only hides the component, so it doesn't trigger onUnmounted. Without clearInterval, the timer keeps running even though the component is gone.

What you will learn