← Back to Vue.js Course | Chapter 4: Components | Lesson 4 of 7

Component lifecycle

Lifecycle hooks are functions Vue calls at key moments: creating, mounting, updating and destroying a component.

In this page:

  1. Component lifecycle
Syntax
markup
export default {
  created() { },
  mounted() { },
  updated() { },
  beforeUnmount() { },
  unmounted() { }
}

Component lifecycle

Hooks include created, mounted, updated, beforeUnmount and unmounted (setup covers the earliest phase). mounted is the place to touch the DOM or start timers, and unmounted or beforeUnmount is where you clean up.

In Vue 3 the Options names beforeDestroy and destroyed were renamed.

Note: Clean up timers and listeners in beforeUnmount to avoid memory leaks.

Example: Component lifecycle

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>{{ msg }}</p>
</div>
<script>
  const log = [];
  const app = Vue.createApp({
    data() { return { msg: "hi" }; },
    created() { log.push("created"); },
    beforeMount() { log.push("beforeMount"); },
    mounted() { log.push("mounted"); this.msg = "changed"; },
    updated() { log.push("updated"); },
    beforeUnmount() { log.push("beforeUnmount"); },
    unmounted() { log.push("unmounted"); },
  });
  app.mount("#app");
  Vue.nextTick(() => { app.unmount(); console.log(log.join(" -> ")); });
</script>
</body>
</html>

<!-- Output:
console: created -> beforeMount -> mounted -> updated -> beforeUnmount -> unmounted
-->
Live Example
Related Topics
Common Mistakes
  1. Accessing the DOM in created
  2. Not cleaning up intervals
  3. Using Vue 2 hook names
Chapter Summary
  • created runs before mounting
  • mounted runs after DOM insertion
  • updated runs after re-render
  • unmounted is for cleanup
🔒

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.