Skip to content
Vue 3

Lifecycle Hooks

Register lifecycle callbacks as composable functions.

By EZ4Code Team
lifecyclehooks

Code

import {
  onBeforeMount, onMounted,
  onBeforeUpdate, onUpdated,
  onBeforeUnmount, onUnmounted
} from "vue";

export function useLogger() {
  onBeforeMount(() => console.log("beforeMount"));
  onMounted(() => console.log("mounted"));
  onBeforeUpdate(() => console.log("beforeUpdate"));
  onUpdated(() => console.log("updated"));
  onBeforeUnmount(() => console.log("beforeUnmount"));
  onUnmounted(() => console.log("unmounted"));
}

// In a component:
// setup() {
//   useLogger();
// }

Explanation

Vue 3 exposes lifecycle hooks as on* functions that register callbacks during component creation. onMounted runs after the DOM is rendered, ideal for fetching data. onBeforeUnmount is the place to clean up timers, listeners, and subscriptions.

More Vue 3 Snippets