In the previous lesson we wrote createApp(App).mount('#app') in src/main.js and the application came to life. Behind that line lie two fundamental concepts: the application instance, which represents the whole app and its global configuration, and component instances, one for each component that appears on screen. Every component instance goes through a lifecycle (it is created, mounted in the DOM, updated and unmounted), and Vue lets us run code at each stage through lifecycle hooks. Understanding this is essential for everyday tasks such as fetching data when a view loads, using timers or releasing resources. We will put it into practice by creating the ReceptionClock component for Colmena Bookings.

Contents

  1. The application instance: createApp and mount
  2. Several applications on the same page
  3. Global configuration with app.config
  4. Application methods: a first look
  5. Coming from Vue 2: from new Vue to createApp
  6. The component instance and the use of this
  7. The component lifecycle
  8. Lifecycle hooks in the Composition API and the Options API
  9. Case study: the ReceptionClock component

  1. The application instance: createApp and mount

Every Vue application starts by creating an application instance with createApp. Let's split the two steps that we have so far been doing in a single line of src/main.js:

// src/main.js
import './assets/main.css'

import { createApp } from 'vue'
import App from './App.vue'

// 1. Create the application instance
const app = createApp(App)

// 2. (Configuration would go here: plugins, global components...)

// 3. Mount it in the DOM
app.mount('#app')
  • createApp(App) takes the root component and returns an app object. Nothing has been rendered yet: the application only exists "in memory".
  • app.mount('#app') looks for the element matching that selector (it also accepts a DOM element directly), creates the root component instance and renders inside the element. It returns the root component instance, not the application.

Important rules:

Rule Consequence
All configuration is done before mount A plugin or global component registered after mounting will have no effect on what has already been rendered
mount is called only once per application To mount it again you would have to call app.unmount() and create a new one
Configuration methods return app They can be chained: createApp(App).use(x).use(y).mount('#app')
mount does not return app Nothing can be chained after mount

  1. Several applications on the same page

createApp is not a single global object: you can create as many independent applications as you need on the same page, each with its own configuration. This is what makes the "embedded widgets" adoption level we saw in the first lesson possible.

Imagine that Colmena's public website (built with another system) wants two independent interactive pieces: a room search box in the header and a contact form in the footer:

import { createApp } from 'vue'
import RoomSearch from './widgets/RoomSearch.vue'
import ColmenaContact from './widgets/ColmenaContact.vue'

// Two completely independent applications
const searchApp = createApp(RoomSearch)
searchApp.mount('#search')

const contactApp = createApp(ColmenaContact)
contactApp.mount('#contact')

Each application has its own app.config, its own global components and its own plugins: configuring one does not affect the other. In an SPA such as Colmena Bookings, you would normally have a single application that controls the whole page.

  1. Global configuration with app.config

The app.config object holds options that affect the whole application. The most useful ones are:

Option What it is for
app.config.errorHandler A function that receives any uncaught error in components (rendering, hooks, event handlers...). Ideal for logging errors to a monitoring service
app.config.warnHandler Receives Vue's warnings during development (by default they are shown in the console)
app.config.globalProperties Adds properties accessible from the template of any component (for example, $format). We will use it when we create formatPlugin in Creating a Vue.js Plugin
app.config.performance Enables performance marks visible in the browser's tools (development only)

Let's add a global error handler to Colmena Bookings:

// src/main.js
import './assets/main.css'

import { createApp } from 'vue'
import App from './App.vue'

const app = createApp(App)

app.config.errorHandler = (error, instance, info) => {
  // error: the Error object that was thrown
  // instance: the component where it happened (may be null)
  // info: a string indicating where it occurred, e.g. "render function" or "mounted hook"
  console.error('[Colmena Bookings] Unhandled error:', error, '| Source:', info)
}

app.mount('#app')

For now it only writes to the console; in a real project it would send the error to an external service. We will go deeper into error handling in Teleport, Suspense and Error Handling.

  1. Application methods: a first look

Besides mount, the application instance offers methods for registering global pieces. We will not use them yet, but you should know that they exist and where they are covered:

Method What it does Where it is covered
app.component(name, component) Registers a global component, usable in any template without importing it Introduction to Components
app.directive(name, directive) Registers a global custom directive (such as v-focus) Custom Directives
app.use(plugin) Installs a plugin: Vue Router, Pinia, Vue I18n or one of your own Using Vue.js Plugins
app.provide(key, value) Provides a value to every component in the app, which retrieves it with inject Component Communication
app.unmount() Unmounts the application and all its components This very section
app.version The version of Vue in use —

This is what main.js will look like a few modules from now (do not write it yet):

createApp(App)
  .use(router)        // module 4
  .use(pinia)         // module 5
  .use(formatPlugin)  // module 7
  .mount('#app')

  1. Coming from Vue 2: from new Vue to createApp

Vue 2 had no concept of an application instance: there was a global Vue constructor and all configuration was applied to it, affecting every instance on the page. If you maintain older code, this table will help you translate it:

Vue 2 Vue 3 Comment
new Vue({ render: h => h(App) }).$mount('#app') createApp(App).mount('#app') The application is created with a function, not a constructor
Vue.component('X', X) app.component('X', X) Registration scoped to one application
Vue.directive('x', x) app.directive('x', x) Likewise
Vue.use(plugin) app.use(plugin) Likewise
Vue.mixin({...}) app.mixin({...}) Discouraged; in Vue 3 composables are preferred
Vue.prototype.$x = ... app.config.globalProperties.$x = ... A global prototype is no longer modified
Vue.config.errorHandler app.config.errorHandler Per-application configuration
beforeDestroy / destroyed hooks beforeUnmount / unmounted Renamed in Vue 3

The great advantage of the new model is isolation: in Vue 2, if a plugin modified Vue, it affected every other app on the page (and your tests). In Vue 3, each application is independent.

  1. The component instance and the use of this

Every time a component appears on screen, Vue creates a component instance: an internal object that holds its state, its props, its functions, a reference to its DOM and its position in the tree. If a component is used three times, there are three instances, each with its own state.

How you access that instance depends on the style you write the component in:

// Options API: "this" is the component instance
export default {
  data() {
    return { freeRooms: 5 }
  },
  methods: {
    bookRoom() {
      this.freeRooms-- // we access the state through this
    }
  }
}
<!-- <script setup>: "this" is not used -->
<script setup>
import { ref } from 'vue'

const freeRooms = ref(5)

function bookRoom() {
  freeRooms.value-- // we access the variable directly
}
</script>
Aspect Options API <script setup> / setup()
Accessing state this.freeRooms freeRooms.value (an ordinary JavaScript variable)
Value of this The component instance Not used (inside setup() it is undefined)
When the code runs In each option, when Vue invokes it setup runs once when the instance is created, before anything else

We will compare both styles in detail in the next lesson.

  1. The component lifecycle

Every component instance goes through the same stages:

  1. Creation: Vue runs setup (and, in the Options API, beforeCreate and created), and prepares the reactive state, computed properties and watchers. There is no DOM yet.
  2. Mounting: Vue renders the template, creates the DOM nodes and inserts them into the page. After mounting, the component's DOM is accessible.
  3. Updating: every time a piece of reactive data used by the template changes, Vue re-renders and applies only the differences to the DOM. This stage repeats as many times as necessary.
  4. Unmounting: when the component is no longer displayed (because the user navigates to another view or a condition hides it), Vue removes its DOM and stops its reactive effects.
flowchart TD
    A["Vue creates the instance"] --> B["setup()"]
    B --> C["beforeCreate / created<br/>(Options API only)"]
    C --> D["onBeforeMount"]
    D --> E["Renders and inserts the DOM"]
    E --> F["onMounted"]
    F --> G{"Does reactive data change?"}
    G -->|"Yes"| H["onBeforeUpdate"]
    H --> I["Re-renders and updates the DOM"]
    I --> J["onUpdated"]
    J --> G
    G -->|"The component is removed"| K["onBeforeUnmount"]
    K --> L["Removes the DOM and stops effects"]
    L --> M["onUnmounted"]

  1. Lifecycle hooks in the Composition API and the Options API

A lifecycle hook is a function that Vue calls automatically at a specific moment. In <script setup> you register them by calling onXxx functions imported from vue; in the Options API you declare them as component options.

Composition API Options API When it runs Typical use
(setup itself) beforeCreate / created When the instance is created, before the DOM Initialising state, firing data requests that do not need the DOM
onBeforeMount beforeMount Just before the DOM is inserted for the first time Rarely needed
onMounted mounted Once the component's DOM is on the page Accessing the DOM, starting timers, integrating external libraries (maps, charts), adding listeners to window
onBeforeUpdate beforeUpdate After the state changes, before the DOM is updated Reading the previous DOM state (e.g. scroll position)
onUpdated updated After the DOM has been updated Actions that depend on the already-updated DOM. Do not modify state here: you would cause a loop
onBeforeUnmount beforeUnmount Before unmounting; the component still works Saving something before leaving
onUnmounted unmounted Once the component has been removed Releasing resources: clearInterval, removing window listeners, closing connections

Notice that there is no onBeforeCreate or onCreated: the code you write directly in <script setup> already runs at that moment.

There are a few more specialised hooks that you will meet in due course: onErrorCaptured (errors from child components, 09-05), onActivated/onDeactivated (components cached with <KeepAlive>, 03-06) and onServerPrefetch (SSR, 09-06).

One essential rule: Composition API hooks must be registered synchronously during setup. Do not call them inside a setTimeout, after an await or inside an event handler: Vue would not know which component they belong to.

  1. Case study: the ReceptionClock component

Colmena's reception wants to see the current time in the application header. It is a perfect lifecycle example: the clock needs a timer that starts when the component is mounted and must be stopped when it is unmounted; otherwise, it would keep running in the background even after the clock has left the screen.

Create the file src/components/ReceptionClock.vue (your own components are covered in depth in module 3; here we focus on its lifecycle):

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

// State: the time formatted as text
const time = ref('')

// We keep the timer's identifier so that we can stop it
let interval = null

function updateTime() {
  time.value = new Date().toLocaleTimeString('en-GB')
}

onMounted(() => {
  updateTime() // show the time straight away
  interval = setInterval(updateTime, 1000) // and refresh it every second
  console.log('[ReceptionClock] mounted: timer started')
})

onUnmounted(() => {
  clearInterval(interval) // release the resource
  console.log('[ReceptionClock] unmounted: timer stopped')
})
</script>

<template>
  <p class="clock">Reception · {{ time }}</p>
</template>

<style scoped>
.clock {
  margin: 0;
  font-variant-numeric: tabular-nums; /* fixed-width digits: the text doesn't "jump around" */
}
</style>

Let's analyse it:

  • const time = ref(''): reactive state holding the time. Every time it changes, the template will update (the updating stage).
  • let interval = null: an ordinary, non-reactive variable. We only use it internally and it does not appear in the template, so it does not need ref.
  • onMounted(...): on mounting, we show the time and schedule setInterval to refresh it every second.
  • onUnmounted(...): on unmounting, clearInterval stops the timer. Without this line, the interval would keep running forever: a memory leak.

Now use it in src/App.vue. We will also add a button to show or hide the clock, so that we can check the unmounting:

<script setup>
import { ref } from 'vue'
import ReceptionClock from './components/ReceptionClock.vue'

const freeRooms = ref(5)
const showClock = ref(true)

function bookRoom() {
  if (freeRooms.value > 0) {
    freeRooms.value--
  }
}

function toggleClock() {
  showClock.value = !showClock.value
}
</script>

<template>
  <header class="header">
    <h1>Colmena Bookings</h1>
    <p>Room booking for the Colmena coworking space</p>
    <ReceptionClock v-if="showClock" />
  </header>

  <main class="content">
    <p>
      Rooms free right now: <strong>{{ freeRooms }}</strong>
    </p>
    <button class="button" @click="bookRoom">Book a room</button>
    <button class="button" @click="toggleClock">Show/hide clock</button>
  </main>
</template>

<!-- The <style scoped> block does not change -->
  • import ReceptionClock from './components/ReceptionClock.vue': in <script setup>, importing a component is all it takes to be able to use it in the template.
  • <ReceptionClock v-if="showClock" />: the v-if directive (which you will study in Conditional Rendering) makes the component exist only when showClock is true. When it becomes false, the component is unmounted; when it goes back to true, a new instance is created and mounted again.

Try it with the console open: when you click "Show/hide clock" you will see the mounting and unmounting messages alternate. In Vue DevTools, ReceptionClock will appear in and disappear from the component tree.

sequenceDiagram
    participant U as User
    participant A as App.vue
    participant R as ReceptionClock
    A->>R: showClock = true: created and mounted
    R->>R: onMounted: setInterval
    loop Every second
        R->>R: time changes: the DOM is updated
    end
    U->>A: Clicks "Show/hide clock"
    A->>R: showClock = false: unmounted
    R->>R: onUnmounted: clearInterval

Common Mistakes and Tips

  • Not cleaning up resources in onUnmounted. Timers, window listeners (addEventListener) or open connections stay active even after the component disappears. Everything you start in onMounted should have its clean-up in onUnmounted.
  • Accessing the DOM before mounting. In the top-level code of <script setup> (or in created) the component's DOM does not exist yet. Use onMounted.
  • Modifying state inside onUpdated. Each change triggers another update, which calls onUpdated again: an infinite loop.
  • Registering hooks asynchronously. setTimeout(() => onMounted(...)) or an onMounted after an await will not work; Vue will show a warning.
  • Using arrow functions for Options API hooks. mounted: () => { this.x } does not work because an arrow function has no this of its own. Write mounted() { ... }.
  • Configuring the app after mount. Register plugins and options before mounting.
  • Tip: a console.log in each hook is an excellent way to understand the lifecycle. Use it to experiment, but remove it from your final code.

Exercises

Exercise 1. Add the onBeforeMount, onBeforeUpdate, onUpdated and onBeforeUnmount hooks to ReceptionClock, each with a console.log. Watch the console for a few seconds and when you hide the clock. How many times does onUpdated run, and why?

Exercise 2. Temporarily remove the clearInterval from onUnmounted and add a console.log('tick') inside updateTime. Hide the clock and explain what happens in the console. Then restore the correct code.

Exercise 3. Rewrite ReceptionClock with the Options API (data, methods, mounted, unmounted).

Solutions

Solution 1.

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

// ... time, interval and updateTime as before ...

onBeforeMount(() => console.log('onBeforeMount: no DOM yet'))
onMounted(() => { /* ... as before ... */ })
onBeforeUpdate(() => console.log('onBeforeUpdate: the time has changed, the DOM has not yet'))
onUpdated(() => console.log('onUpdated: DOM updated'))
onBeforeUnmount(() => console.log('onBeforeUnmount: the clock is still working'))
onUnmounted(() => { /* ... as before ... */ })

onBeforeUpdate and onUpdated run once per second, because time changes every second and the template is re-rendered. The order in the console on mounting is onBeforeMount → onMounted; on hiding, onBeforeUnmount → onUnmounted.

Solution 2. Although the clock disappears from the screen, tick keeps appearing every second: the timer is still alive. And if you show the clock again, the new instance creates another interval, so you will see two ticks per second, then three... It is a classic memory leak. That is why clearInterval in onUnmounted is mandatory.

Solution 3.

<script>
export default {
  data() {
    return {
      time: '',
      interval: null
    }
  },
  methods: {
    updateTime() {
      this.time = new Date().toLocaleTimeString('en-GB')
    }
  },
  mounted() {
    this.updateTime()
    this.interval = setInterval(this.updateTime, 1000)
  },
  unmounted() {
    clearInterval(this.interval)
  }
}
</script>

<template>
  <p class="clock">Reception · {{ time }}</p>
</template>

Notice that everything is accessed through this and that mounted/unmounted are regular methods, not arrow functions. Storing interval in data makes it reactive for no reason; an alternative is to assign it as this.interval without declaring it in data. Afterwards, go back to the <script setup> version, which is the one we will keep in the project.

Conclusion

You have seen that createApp creates an independent application instance, which is configured (with app.config, app.use, app.component...) before calling mount exactly once, and that this model replaces Vue 2's global new Vue, providing isolation between applications. Every component on screen is an instance with its own state and its own lifecycle: creation, mounting, updates and unmounting. Using the onMounted and onUnmounted hooks you have created ReceptionClock, which starts its timer when it appears and releases it when it disappears, and you have added a global errorHandler to Colmena Bookings.

Throughout the lesson you have seen the same component written in two ways: with <script setup> and with the Options API. In the next lesson, Options API and Composition API, we will compare both styles in depth and explain why the course uses <script setup> by default.

New edition · October 2026

Vue.js Course

Module 1: Introduction to Vue.js

Module 2: Vue.js Basics

Module 3: Vue.js Components

Module 4: Vue Router

Module 5: State Management with Vuex and Pinia

Module 6: Vue.js Directives

Module 7: Vue.js Plugins

Module 8: Testing in Vue.js

Module 9: Advanced Vue.js Concepts

Module 10: Building and Deploying Vue.js Applications

Module 11: Real-World Vue.js Projects

© Copyright 2026. All rights reserved