Support Online
Skip to main content

Vue.js Lifecycle Hooks: When Should Your Code Run?

What Will You Learn in This Guide?

This guide explains the lifecycle of Vue.js components.
It clarifies when and why your code runs.
You prevent errors caused by using the wrong hook.

Technical Summary

  • Subject: Vue.js Lifecycle Hooks
  • Problem: The code runs at the wrong time
  • Solution: Using the right hook in the right place
  • Stages: Create → Deploy → Update → Destroy

What are Lifecycle Hooks?

Lifecycle hooks represent the lifecycles of the component.
There are special functions running in each thread.
This way you control the inner workings of Vue.


1️⃣ Initialization

These hooks run before the DOM is created.
It is the only phase that runs during SSR (Nuxt.js).
this.$el access is not available.

beforeCreate

export default {
beforeCreate() {
console.log('Bileşen başlatılıyor.')
}
}
  • Reactive data is not ready yet.

created


export default {
data() {
return { mesaj: 'Merhaba' }
},
created() {
this.mesaj = 'Güncellendi'
}
}
  • It is the most appropriate stage for API requests.

2️⃣ Insertion Hooks (DOM Insertion)

  1. These hooks run before and after the first render.
  2. Does not work in SSR environment.

####beforeMount


export default {
beforeMount() {
console.log('DOM henüz oluşturulmadı.')
}
}
  • It is the last step before HTML is printed on the screen.

####mounted


export default {
mounted() {
console.log(this.$el.textContent)
}
}
  • It is the most accurate stage for DOM manipulation.

3️⃣ Update Hooks (Re-render)

  1. Reactive is triggered when data changes.
  2. Used for debugging and performance measurement.
⚠️ Tip:
  1. Choose watch or computed to monitor data.

####beforeUpdate


export default {
beforeUpdate() {
console.log('DOM henüz güncellenmedi.')
}
}
  • There is new data, the screen is old.

updated


export default {
updated() {
console.log('DOM güncellendi.')
}
}
  • The screen now reflects the new data.
⚠️ Attention:

Changing the state in updated may create an infinite loop.


4️⃣ Destruction Hooks (Teardown)

  1. It runs while the component is being removed.
  2. It is critical to prevent memory leaks.

beforeDestroy


export default {
beforeDestroy() {
console.log('Temizlik başlıyor.')
}
}
  • Clear events and timers here.

destroyed


export default {
destroyed() {
console.log('Bileşen tamamen silindi.')
}
}
  • Suitable for analytical or logging operations.

❓ Frequently Asked Questions

1. Where should the API request be made? → created

2. Where should DOM measurement be done? → mounted

3. Which hooks work in SSR? → beforeCreate, created

4. Can I change the state in updated? → Not recommended, infinite loop may occur.


Result

Using lifecycle hooks correctly increases performance. It reduces errors, makes the code predictable.

You can achieve maximum performance by publishing your Vue.js projects on the GenixNode infrastructure.