...

/

Lifecycle Hooks

Lifecycle Hooks

Explore the various lifecycle hooks and when we would use them.

When a new component instance is created, it goes through various stages. At each stage, it can run a function to perform a task, and these are called lifecycle hooks. The lifecycle begins before a component has been created and ends when it is unmounted, with various stages in between.

Overview

Lifecycle hooks can be used with both the Options API and Composition API. Here is a comparison of the names of the hooks in both:

Lifecycle Hook Names

Options API

Composition API

Called When

beforeCreate

setup

The component is yet to be created, no reactive data is accessible

created

setup

The component is created and reactive state is ready

beforeMount

onBeforeMount

Reactive state is ready, but the component DOM tree is not yet created, this is the HTML/Node structure of our page being created

mounted

onMounted

Component DOM tree is created, and child components have been mounted

beforeUpdate

onBeforeUpdate

The component is about to update the DOM

updated

onUpdated

DOM tree has been updated

beforeUnmount

onBeforeUnmount

A component is ready to be unmounted

unmounted

onUnmounted

All child components are unmounted and reactive effects have stopped

We’ll focus on the Composition API version, but it performs the same functionality as the Options API. However, the auto-import of these hooks is taken care of for us by Nuxt. This means the functions are ...