Vue Lifecycle Hooks: Running Code at the Right Time
Vue lifecycle hooks are your cues to run code at specific moments in a component's life. Use `onMounted` to fetch data or `onUnmounted` to clean up timers. The main footgun is that hooks must be registered synchronously during setup, not in an async callback.
WHY IT EXISTS Components aren't static; they are created, rendered, updated, and destroyed. We need a reliable way to perform actions—like fetching data or cleaning up resources—that are tied to these specific moments in a component's existence. Lifecycle hooks provide these predictable entry points.
THE MENTAL MODEL Think of a component's lifecycle like the stages of a play. setup is building the set. onMounted is the curtain rising for the first time. onUpdated is a scene change. onUnmounted is the final curtain call and striking the set. These hooks are your cues from the director (Vue) to perform a specific action at exactly the right moment.
HOW IT WORKS When Vue creates a component instance, it moves through a predefined sequence. It initializes data, compiles the template, mounts the component to the DOM, watches for data changes to trigger updates, and eventually unmounts it. At each key stage, Vue checks for and executes any corresponding hook function you've registered. In the Composition API, you import and call hooks like onMounted(). In the older Options API, you define them as methods like mounted().
WHEN TO USE IT Use hooks for managing "side effects"—tasks that interact with things outside the component itself. The most common uses are: fetching data from an API when the component is mounted (onMounted), cleaning up timers or manual event listeners when the component is destroyed (onUnmounted), or interacting with a non-Vue library after an update (onUpdated).
WHEN NOT TO USE IT Avoid placing hooks inside asynchronous callbacks like setTimeout or a Promise.then(). Vue must associate the hook with the component instance synchronously during the setup phase. If you register it late, Vue won't know which component it belongs to, and it will fail to run. Also, in the Options API, do not use arrow functions for hooks (mounted: () => {}) because you will lose the this context that points to the component instance.
ONE CANONICAL EXAMPLE To fetch user data when a profile component first appears, you use onMounted. This ensures the DOM is ready and you aren't trying to fetch data for a component that hasn't been rendered yet. For example, in <script setup>: import { ref, onMounted } from 'vue'; const user = ref(null); onMounted(async () => { const res = await fetch('/api/user'); user.value = await res.json(); }); This code runs once, right after the component is added to the page.
Read the original → vuejs.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.