Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 87 ยท Lifecycle and Composition API

Lifecycle Hooks

Learn the Vue 3 lifecycle hooks - onBeforeMount, onMounted, onUpdated, onUnmounted - the exact order they run in for parents and children, and how to clean up timers and listeners.

Every component instance goes through the same stages: it is created, its DOM is built and inserted, it updates whenever its reactive state changes, and eventually it is removed. Lifecycle hooks are functions you register to run your own code at those moments, for example to measure an element once it exists, to start a timer, or to stop that timer when the component goes away.

In the Composition API each hook is a function you import from vue and call inside setup() (or at the top level of <script setup>): onMounted, onUpdated, onUnmounted and a few relatives. This lesson shows what each hook is for, the exact order in which parent and child hooks run, and the most important habit that goes with them: whatever you start, you stop.

The stages of a component

There are two pairs of hooks for the first render and the removal, and one pair for updates. Each pair has a "before" and an "after" hook.

Hook Runs Typical use
setup() itself Before anything else Create state, register hooks
onBeforeMount Just before the first DOM is created Rarely needed
onMounted After the component's DOM is inserted Read the DOM, start timers, add listeners, first fetch
onBeforeUpdate After state changed, before the DOM is patched Read the DOM as it is before the change
onUpdated After the DOM was patched Read the DOM as it is after the change
onBeforeUnmount Just before teardown Last chance to use the DOM and state
onUnmounted After the component was removed Clear timers, remove listeners, close connections
flowchart TB
    S["setup()"] --> BM["onBeforeMount"]
    BM --> M["onMounted<br/>DOM exists"]
    M --> U{"reactive state<br/>changes?"}
    U -->|"yes"| BU["onBeforeUpdate"]
    BU --> UP["onUpdated"]
    UP --> U
    U -->|"component removed"| BUN["onBeforeUnmount"]
    BUN --> UN["onUnmounted"]

A component runs setup once, mounts once, updates as often as needed, then unmounts once.

setup() takes the place of the old "created" stage. Code that you would have put in a created hook goes straight into setup(). There is no onCreated in the Composition API.

Seeing the order for yourself

The best way to learn the hooks is to watch them. The example below has a parent and a child. Every hook writes a line into a log under the app. The log is a plain DOM element outside Vue, so writing to it does not trigger more updates.

Watch the lifecycle of a parent and a child

When the page loads, the log starts like this:

TEXT
parent: setup
parent: beforeMount
child: setup
child: beforeMount
child: mounted
parent: mounted

Read it carefully, because it answers the most common question about lifecycles. The parent starts first (it has to render before it knows a child exists), but the parent's mounted runs last, because a parent counts as mounted only once all its children are mounted. That means inside a parent's onMounted you can safely rely on its child components' DOM.

Now press "Increment". The child receives a new prop, so both components re-render, and the log shows parent: beforeUpdate, child: beforeUpdate, child: updated, parent: updated: the same inner-first pattern. Press "Remove child": the parent updates, and the child runs beforeUnmount and unmounted while the parent patches.

Updates are batched. If you change three refs in one click handler, onUpdated runs once, after the DOM reflects all three changes. Read DOM update timing and nextTick for the details.

Doing work after mount

onMounted is where your component first has a real DOM. Anything that needs an actual element belongs here: focusing an input, measuring a box, initializing a charting library on a container.

Focus and measure in onMounted

The input is focused as soon as the page is ready and the status changes from "not measured yet" to "mounted, the field is an input". Before onMounted, the template ref nameInput is still null, which is why touching it inside setup() itself would fail. More about refs to elements in Template refs and exposing methods.

Two other places also run code after mount in practice: loading data (see Fetching data) and subscribing to the outside world, which brings us to cleanup.

onMounted does not run during server-side rendering, because there is no DOM on the server. Code that needs window or document should live in onMounted for that reason. See Server-side rendering and hydration.

Always clean up

A timer, an event listener on window, a WebSocket, an observer: all of these live outside your component. If the component is removed and you do nothing, they keep running and keep holding references. The rule is symmetrical: whatever you set up in onMounted, tear down in onUnmounted (or onBeforeUnmount).

The next example runs a ticking timer in a component that the page can add and remove. A counter in the parent tracks how many timers are alive at any moment.

A timer that cleans up after itself

The counter shows "Running timers: 1" while the ticker is visible and goes to 0 when you press "Stop". Remove the clearInterval line and the number would still read 0 or 1, but the interval would keep firing for a component nobody can see. That is a leak, and it never shows up on screen, which is why it is easy to miss. Check your own code for the pairing: setInterval with clearInterval, addEventListener with removeEventListener, new Observer with disconnect.

Hooks inside composables

A lifecycle hook belongs to the component instance that is currently running its setup. So you can call hooks from any function as long as that function is itself called synchronously from setup(). This is exactly how composables bundle setup and cleanup into one reusable unit, which the next lesson builds on.

JavaScript
import { onMounted, onUnmounted } from "vue";

export function useEventListener(target, eventName, handler) {
  onMounted(() => target.addEventListener(eventName, handler));
  onUnmounted(() => target.removeEventListener(eventName, handler));
}

A component then writes one line, useEventListener(window, "resize", update), and gets the correct cleanup for free. Two limits apply. Hooks must be registered synchronously during setup: calling onMounted inside a setTimeout or after an await in a plain setup() fails because Vue no longer knows which component is current. And a hook called outside any setup prints a warning in development.

created versus mounted

A frequent question, especially when reading Vue 2 code, is the difference between the created and mounted hooks of the Options API:

created mounted
Reactive data and methods ready ready
Computed and watchers set up set up
DOM of the component does not exist (this.$el is null) exists and is in the page
Template refs not available available
Runs on the server (SSR) yes no
Typical use start a fetch, set up non-DOM state measure elements, focus an input, start a third-party widget

Start data loading in created (or directly in setup()) so the request begins as early as possible; use mounted only when you need the DOM.

What exists in created and mounted

The first line shows that $el is null in created; the second shows that in mounted the root element and the ref are available.

Other hooks you will meet

  • onErrorCaptured catches errors thrown by descendant components, which lets a parent show a fallback.
  • onActivated and onDeactivated run when a component inside <KeepAlive> becomes visible or is cached (Teleport and KeepAlive).
  • onRenderTracked and onRenderTriggered are debugging hooks that report which reactive values the render depends on or was triggered by.
  • onServerPrefetch exists for server rendering.

If you ever meet a component whose behavior you do not understand, adding a logging hook like the ones in the first example is a quick way to see what runs when.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A parent component renders one child. In which order do the two mounted hooks run?

    A parent counts as mounted only after all its children are mounted, so the child's onMounted runs before the parent's.
  2. 2. Where should you put code that needs a real DOM element, such as calling focus() on an input?

    The DOM exists only after mounting. In setup() and onBeforeMount the element has not been created yet, so a template ref is still null.
  3. 3. A component starts a setInterval in onMounted. What must it also do?

    Vue does not know about timers, listeners or sockets you create yourself. Without cleanup they keep running after the component is gone.
  4. 4. Which statement about calling lifecycle hooks in a composable is true?

    A hook attaches to the component whose setup is currently running. Calling it synchronously from setup works; calling it later (after an await or in a timeout) does not.

Summary

  • setup() runs first; onBeforeMount and onMounted follow, then onBeforeUpdate and onUpdated on every re-render, and finally onBeforeUnmount and onUnmounted.
  • A parent's onMounted runs after all of its children have mounted; updates and unmounts follow the same inner-first pattern for the "after" hooks.
  • Use onMounted for anything that needs a real DOM element or starts something that runs outside Vue.
  • Pair every setup with a teardown in onUnmounted: timers, listeners, observers and connections.
  • Hooks can live inside composables, as long as they are registered synchronously during setup().
  • onMounted does not run on the server.

Next, turn this setup-and-cleanup pattern into reusable functions: Composables.