← Back to Vue.js Course | Chapter 9: Composables & Composition API | Lesson 5 of 7

Lifecycle hooks in setup

In the Composition API lifecycle hooks are functions such as onMounted and onUnmounted that you call inside setup.

In this page:

  1. Lifecycle hooks in setup
Syntax
markup
import { onMounted, onUnmounted } from 'vue';

setup() {
  onMounted(() => {
    // runs after mounting
  });
  onUnmounted(() => {
    // cleanup
  });
}

Lifecycle hooks in setup

Import or access onMounted, onUpdated, onUnmounted, onBeforeMount and friends and pass them a callback. You can call the same hook several times, which lets composables register their own setup and cleanup logic. created and beforeCreate are replaced by setup itself.

Note: Clean up timers and listeners in onUnmounted inside the same composable that created them.

Example: Lifecycle hooks in setup

markup
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app"><p>{{ ticks }} ticks</p></div>
<script>
  const events = [];
  let tickRef;
  const app = Vue.createApp({
    setup() {
      const ticks = Vue.ref(0);
      tickRef = ticks;
      let timer;
      Vue.onMounted(() => { events.push("mounted"); timer = setInterval(() => ticks.value++, 5); });
      Vue.onUnmounted(() => { events.push("unmounted"); clearInterval(timer); });
      return { ticks };
    },
  });
  app.mount("#app");
  setTimeout(() => { app.unmount(); console.log(events.join(" -> "), "| ticks counted while mounted:", tickRef.value > 0); }, 40);
</script>
</body>
</html>

<!-- Output:
console: mounted -> unmounted | ticks counted while mounted: true
-->
Live Example
Related Topics
Common Mistakes
  1. Calling hooks outside setup
  2. Forgetting cleanup
  3. Expecting a created hook
Chapter Summary
  • onMounted, onUpdated, onUnmounted
  • Call them inside setup
  • Several calls are allowed
  • setup replaces created
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.