Vue Lifecycle
Run component logic during creation, mounting, updates, and removal.
Overview
Every Vue component moves through a lifecycle from setup to removal. Lifecycle hooks run code at specific stages, providing appropriate places to fetch data, interact with rendered DOM, connect external libraries, observe updates, and release timers, listeners, or connections.
Key concepts
- Creation prepares reactive state and logic
- Mounting inserts rendered DOM
- Updates patch DOM after state changes
- Unmounting requires resource cleanup
What is a Lifecycle?
A component is created, rendered into the page, updated when reactive dependencies change, and eventually removed. Vue exposes hooks around these stages so code can run at the correct time.
Create
↓
Mount
↓
Update (zero or many times)
↓
UnmountWhy do we need Lifecycle Hooks?
A weather component may request forecast data, initialize a chart after its container exists, react to selected-city changes, and dispose of listeners when the user navigates away. Hooks keep each task aligned with the component stage it depends on.
Create Stage
Vue initializes component props, reactive state, computed values, watchers, and methods before rendering. In the Options API, beforeCreate and created surround much of this initialization. With the Composition API, setup code itself runs during component creation.
export default {
data: () => ({ status: "ready" }),
created() {
console.log("Component logic is created");
}
};The component DOM is not mounted during created, so template refs and rendered elements are not yet available.
Mount Stage
Vue renders the component and inserts it into the document. mounted or onMounted runs after the component's DOM has been created.
export default {
mounted() {
console.log("Component is mounted");
}
};- Access template refs
- Measure rendered elements
- Initialize a DOM-dependent library
- Start a timer or observer
- Register browser listeners
API requests do not inherently require mounted DOM. They can also start in setup, created, a store action, a route loader, or in response to a user action depending on the architecture.
Update Stage
When reactive state used during rendering changes, Vue schedules a DOM patch. updated or onUpdated runs after the component's DOM has been updated.
<script setup>
import { nextTick, ref } from "vue";
const count = ref(0);
async function incrementAndMeasure() {
count.value++;
await nextTick();
// The DOM now displays the new count.
}
</script>Use nextTick when one action needs to wait for its scheduled DOM update. Avoid changing state unconditionally inside an update hook because that can trigger an update loop.
Unmount Stage
A component unmounts when routing, conditional rendering, or parent removal takes it out of the application. beforeUnmount runs while the instance is still active; unmounted or onUnmounted runs after its rendered tree and reactive effects have been stopped.
- Clear intervals and timeouts
- Remove window or document listeners
- Disconnect observers
- Cancel pending requests when appropriate
- Close sockets or subscriptions
- Dispose of third-party library instances
Composition API Lifecycle Hooks
<script setup>
import { onMounted, onUnmounted } from "vue";
function handleResize() {
console.log(window.innerWidth);
}
onMounted(() => {
window.addEventListener("resize", handleResize);
});
onUnmounted(() => {
window.removeEventListener("resize", handleResize);
});
</script>Lifecycle Hook reference
| Options API | Composition API | When it runs |
|---|---|---|
| beforeCreate | setup execution covers this phase | Before Options API state initialization |
| created | setup execution covers this phase | After Options API state is prepared |
| beforeMount | onBeforeMount | Before initial DOM insertion |
| mounted | onMounted | After component DOM is mounted |
| beforeUpdate | onBeforeUpdate | Before a reactive DOM patch |
| updated | onUpdated | After the DOM patch |
| beforeUnmount | onBeforeUnmount | Before component removal |
| unmounted | onUnmounted | After removal and effect cleanup |
| errorCaptured | onErrorCaptured | When a descendant error is captured |
Timer cleanup example
<script setup>
import { onMounted, onUnmounted, ref } from "vue";
const seconds = ref(0);
let timer;
onMounted(() => {
timer = window.setInterval(() => seconds.value++, 1000);
});
onUnmounted(() => {
window.clearInterval(timer);
});
</script>Watchers and Lifecycle Hooks
A lifecycle hook responds to a component stage. A watcher responds to a specific reactive value. Use watch when logic should run because a city, query, or other dependency changed rather than after every component update.
| Need | Use |
|---|---|
| DOM is ready | mounted / onMounted |
| A specific value changed | watch |
| Wait for one DOM patch | nextTick |
| Release external resources | unmounted / onUnmounted |
Real-life example
A news page creates its state, mounts its interface, requests or receives articles, rerenders when article data changes, and disconnects live-update subscriptions when the user leaves. Lifecycle hooks keep setup and cleanup paired.
Common beginner mistakes
- Accessing template refs before mounting
- Forgetting timer or listener cleanup
- Changing reactive state repeatedly inside updated
- Using onUpdated when watch targets the need more precisely
- Assuming mounted means every child or remote resource is fully ready
- Registering lifecycle hooks asynchronously instead of during setup
Best practices
- Choose hooks based on actual stage requirements
- Keep hook callbacks focused
- Pair every external setup with cleanup
- Use watch for dependency-specific reactions
- Use nextTick for a single pending DOM update
- Extract reusable lifecycle behavior into composables
- Handle request cancellation and stale responses
- Avoid expensive work after every update
Key takeaways
- Components pass through create, mount, update, and unmount stages
- Hooks run code around those stages
- onMounted is appropriate for rendered-DOM work
- Reactive changes schedule efficient DOM patches
- nextTick waits for a pending patch
- watch responds to specific state
- onUnmounted cleans external resources
- Correct lifecycle use prevents leaks and update loops