Lesson 03-Vue3 Lifecycle Deep Dive

Vue 3’s lifecycle is key to understanding the process of component loading, rendering, updating, and destruction. Lifecycle hooks provide opportunities to execute code at specific stages, which is essential for tasks like initialization, reactive updates, and resource cleanup.

Lifecycle Hooks

Options API Lifecycle Hooks

In Vue 3’s Options API, lifecycle hooks are similar to Vue 2 but include some adjustments and new additions. Below are the lifecycle hooks in the Options API:

  • beforeCreate: Called after instance initialization, before data observation (data observer) and event/watcher setup.
  • created: Called immediately after the instance is created. At this point, data observation, properties, methods, and event/watcher callbacks are set up, but the mounting phase has not started, and the $el property is not yet available.
  • beforeMount: Called before mounting begins, when the render function is first invoked.
  • mounted: Called after the instance’s el is replaced by the newly created vm.$el and mounted to the DOM. If the root instance mounts an in-document element, vm.$el is in the document when mounted is called.
  • beforeUpdate: Called before the virtual DOM is patched, during server-side rendering, and only when the component re-renders.
  • updated: Called after the virtual DOM is patched, during server-side rendering, and only when the component re-renders.
  • activated: Called when a keep-alive component is activated.
  • deactivated: Called when a keep-alive component is deactivated.
  • beforeUnmount: Called before the instance is destroyed. The instance is still fully functional at this stage.
  • unmounted: Called after the instance is destroyed. All directives are unbound, event listeners are removed, and child instances are destroyed.

Composition API Lifecycle Hooks

Vue 3’s Composition API introduces a set of lifecycle hooks as functions, usable within the setup() function. Below are the Composition API lifecycle hooks:

  • onBeforeMount: Called when the beforeMount hook is triggered.
  • onMounted: Called when the mounted hook is triggered.
  • onBeforeUpdate: Called when the beforeUpdate hook is triggered.
  • onUpdated: Called when the updated hook is triggered.
  • onActivated: Called when the activated hook is triggered.
  • onDeactivated: Called when the deactivated hook is triggered.
  • onBeforeUnmount: Called when the beforeUnmount hook is triggered.
  • onUnmounted: Called when the unmounted hook is triggered.
  • onErrorCaptured: Called when an error from a descendant component is captured.

Vue 3 Lifecycle Overview

Vue 3’s lifecycle is divided into several phases: initialization, mounting, updating, and destruction. Each phase has corresponding lifecycle hooks for executing specific tasks.

Initialization Phase

During the initialization phase, Vue creates the component instance and sets up data and methods. The hooks in this phase include:

  • setup(): A new lifecycle hook in Vue 3 for the initialization phase. Called immediately after instance creation, before properties and methods are initialized. Within setup(), you can define reactive state, computed properties, watchers, and more.

Mounting Phase

When the component is added to the DOM, the mounting phase hooks are triggered:

  • beforeMount: Called before the component is mounted to the DOM.
  • mounted: Called after the component is mounted to the DOM. At this point, you can access real DOM nodes, perform DOM operations, or initialize external libraries.
export default {
  setup() {
    const message = ref('Hello Vue 3!');
    
    onMounted(() => {
      console.log('Component has been mounted.');
    });

    return { message };
  }
};

Updating Phase

When reactive data changes, the updating phase hooks are triggered:

  • beforeUpdate: Called before the component updates, allowing access to the old DOM nodes.
  • updated: Called after the component updates, providing access to the latest DOM nodes.
export default {
  setup() {
    const message = ref('Hello Vue 3!');
    
    watch(message, () => {
      console.log('Data has changed, component will update.');
    });

    onUpdated(() => {
      console.log('Component has been updated.');
    });

    return { message };
  }
};

Destruction Phase

When the component is destroyed, the destruction phase hooks are triggered:

  • beforeUnmount: Called before the component is destroyed, when the instance is still fully functional.
  • unmounted: Called after the component is fully destroyed. Use this to clean up resources, such as canceling event listeners or clearing timers.
export default {
  setup() {
    const timer = ref(null);
    
    onMounted(() => {
      timer.value = setInterval(() => {
        console.log('Timer tick.');
      }, 1000);
    });

    onBeforeUnmount(() => {
      clearInterval(timer.value);
    });

    return {};
  }
};

Asynchronous Update Hooks

Vue 3 provides hooks for asynchronous updates, allowing you to wait for DOM updates after data changes:

  • onActivated: Called when a keep-alive cached component is activated.
  • onDeactivated: Called when a keep-alive cached component is deactivated.
export default {
  setup() {
    onActivated(() => {
      console.log('Component has been activated.');
    });

    onDeactivated(() => {
      console.log('Component has been deactivated.');
    });

    return {};
  }
};

Error Handling Hooks

Vue 3 provides error handling hooks to capture and manage errors within components:

  • onErrorCaptured: Called when an error from a descendant component is captured, useful for logging errors or implementing recovery logic.
export default {
  setup() {
    onErrorCaptured(error => {
      console.error('An error occurred:', error);
      return false; // Prevent error propagation
    });

    return {};
  }
};

Code Analysis

  • Lifecycle Hooks: Options and Composition APIs provide flexible ways to hook into component lifecycle stages.
  • Initialization: setup() centralizes reactive state and logic setup in Vue 3.
  • Mounting/Updating: Hooks like onMounted and onUpdated enable DOM interaction and reactive updates.
  • Destruction: onUnmounted ensures proper resource cleanup.
  • Specialized Hooks: onActivated, onDeactivated, and onErrorCaptured address advanced use cases like caching and error handling.
  • Practical Usage: Lifecycle hooks are critical for initializing resources, reacting to data changes, and cleaning up to prevent memory leaks.

Share your love