Vue Lifecycle Hooks
Every Vue component instance goes through a series of initialization steps when it's created - setting up data observation, compiling the template, mounting the instance to the DOM, and updating the DOM when data changes. Along the way, it also runs functions called lifecycle hooks, giving you the opportunity to add your own code at specific stages.
Common Lifecycle Hooks
onMounted
onMounted() is called after the component has been mounted to the DOM. This is the perfect place to:
- Access DOM elements
- Set up event listeners
- Fetch initial data
- Initialize third-party libraries
<script setup>
onMounted(() => {
console.log('Component is now in the DOM!')
})
</script>
onUpdated
onUpdated() is called after the component has updated its DOM tree due to a reactive state change.
<script setup>
onUpdated(() => {
console.log('Component has updated!')
})
</script>
Warning: Avoid changing state inside onUpdated as it can cause infinite update loops.
onUnmounted
onUnmounted() is called after the component has been unmounted. Use it to clean up:
- Event listeners
- Timers and intervals
- Subscriptions
- Third-party library instances
<script setup>
let intervalId
onMounted(() => {
intervalId = setInterval(() => {
console.log('Tick')
}, 1000)
})
onUnmounted(() => {
clearInterval(intervalId)
})
</script>
The Lifecycle Flow
- Setup - Component is created, reactive state is set up
- onMounted - Component is added to the DOM
- onUpdated - Component re-renders due to state changes (can happen multiple times)
- onUnmounted - Component is removed from the DOM
Challenge
Create a timer component that:
- Starts counting seconds when the component is mounted
- Updates the display every second
- Shows a log message when the component updates
- Cleans up the timer when unmounted
To complete the challenge:
- Create a
refcalledsecondsinitialized to 0 - In
onMounted, set up an interval that incrementssecondsevery 1000ms - Store the interval ID so you can clear it later
- In
onUnmounted, clear the interval - Optionally, add
onUpdatedto log when the component updates
Tip: Don't forget to store your interval ID in a variable outside the lifecycle hooks so you can access it in onUnmounted!
If you get stuck, you can check the solution by clicking the button below.
Understanding lifecycle hooks is crucial for managing side effects and cleanup in Vue components. Next, we'll explore the Composition API in more depth.