Lifecycle hooks
Running code when a Vue component mounts, updates, and unmounts with onMounted and friends, plus cleanup, the sync-registration rule, and SSR.
Lifecycle hooks
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- `<script setup>` itself runs once, when the component instance is created and before any DOM exists. Lifecycle hooks let you register code for the later moments: after mount, around updates, and before and after unmount.
- `onMounted` is where the component's DOM exists, so it is the place to measure elements, focus inputs, and start non-Vue libraries that need a real element. A parent's `onMounted` runs after all of its children's.
- Anything a component starts, such as a timer, a global event listener, or a subscription, should be stopped in `onUnmounted` (or `onBeforeUnmount`), or it keeps running after the component is gone.
- Hooks must be registered synchronously while setup runs, because Vue attaches them to the component instance that is currently being set up. Calling `onMounted` from a `setTimeout` callback registers nothing.
- `onUpdated` runs after any re-render, for any reason, so it is rarely the right tool. A watcher on the specific state you care about, with `flush: 'post'` if you need the DOM, is more precise.
- None of the mount, update, or unmount hooks run during server-side rendering, which is why browser-only code belongs in `onMounted` and not at the top of `<script setup>`.
Setup runs once. Some code has to wait.
Everything in <script setup> runs a single time, when Vue creates the component instance. That is the right moment for declaring state, computeds, and watchers. It is too early for anything that needs the component to be on the page:
<script setup>
const el = document.querySelector('.chart') // null: nothing has rendered yet
</script>
And it says nothing about the other end of the component’s life. When a v-if turns false or the user goes to another route, the component is removed. Any timer or global listener it started keeps running unless something stops it.
Lifecycle hooks are how a component registers code for those later moments. Think of a stage crew: setup is building the set backstage, mounting is the curtain going up, and unmounting is striking the set. Some jobs, like testing the lights or hanging the backdrop, can only happen once the set is actually on stage, and someone has to take it all down at the end.
The hooks, in order
<script setup>
import {
onBeforeMount, onMounted,
onBeforeUpdate, onUpdated,
onBeforeUnmount, onUnmounted,
} from 'vue'
// setup body: runs first, once
onBeforeMount(() => { /* about to render and insert DOM for the first time */ })
onMounted(() => { /* DOM exists and is in the document */ })
onBeforeUpdate(() => { /* state changed, DOM about to be patched */ })
onUpdated(() => { /* DOM has been patched after a change */ })
onBeforeUnmount(() => { /* still fully working, about to be removed */ })
onUnmounted(() => { /* removed: clean up anything left running */ })
</script>
There is no onCreated. The setup body itself plays that role, which is why the Options API’s beforeCreate and created have no Composition API equivalent. You can call the same hook more than once, and the callbacks run in the order they were registered. That is what lets several composables each register their own onMounted in one component.
Order across components matters too. A parent’s onMounted runs after all of its children have mounted, because the parent’s DOM is not complete until theirs is.
onMounted: the DOM is here
onMounted is the workhorse. The element exists, so you can measure it, focus it, or hand it to a library that needs a real DOM node:
<script setup>
import { onMounted, onUnmounted, useTemplateRef } from 'vue'
import { createChart } from 'some-chart-lib'
const canvas = useTemplateRef('canvas')
let chart
onMounted(() => {
chart = createChart(canvas.value)
})
onUnmounted(() => {
chart.destroy()
})
</script>
<template>
<canvas ref="canvas" />
</template>
useTemplateRef (Vue 3.5+) is how you get hold of the element. It and the older ref="name" pattern are covered in template refs and defineExpose. The point here is timing: a template ref is null during setup and populated by the time onMounted runs.
Cleanup: whatever you start, stop
import { ref, onMounted, onUnmounted } from 'vue'
const width = ref(window.innerWidth)
const onResize = () => { width.value = window.innerWidth }
onMounted(() => window.addEventListener('resize', onResize))
onUnmounted(() => window.removeEventListener('resize', onResize))
Without the onUnmounted, every mount of this component adds one more listener, and each one keeps its dead component’s state alive in memory. The same goes for setInterval, WebSocket connections, observers like IntersectionObserver, and subscriptions to external stores. Pair every start with a stop.
One thing you do not have to clean up by hand: watchers and computeds created synchronously in setup are stopped automatically when the component unmounts.
Updates: usually a watcher instead
onBeforeUpdate and onUpdated fire around any re-render of the component, whatever caused it. That makes them blunt. If you want to react to one specific change, a watcher on that state says so precisely, and flush: 'post' makes it run after the DOM is patched. Never change state inside onUpdated: it causes another update, which calls onUpdated again.
For a one-off “after this change, once the DOM catches up,” await nextTick() in the code that made the change is simpler still.
The synchronous registration rule
Hooks do not take a component argument. Vue attaches each one to whichever component instance is being set up at the moment of the call. So they must be called synchronously during setup:
// Works: called during setup, even if from inside a composable that setup calls
useWindowSize()
// Does not work: setup is long over when this runs
setTimeout(() => {
onMounted(() => { /* never registered */ })
}, 0)
This is the same reason composables have to be called at the top level of <script setup>. It is Vue’s counterpart to React’s rules of hooks, though the cause is different: Vue only needs to know which instance is current, not the call order.
The rest of the family, and SSR
A few more hooks belong to specific features:
onActivated/onDeactivatedrun when a component cached by<KeepAlive>is shown or hidden. See KeepAlive and cached components.onErrorCapturedcatches errors from descendant components. See error handling in Vue.onServerPrefetchruns async work during server rendering.onRenderTracked/onRenderTriggeredare development-only debugging hooks that report which dependency caused a render.
During server-side rendering, setup runs on the server, but none of the mount, update, or unmount hooks do, since there is no DOM there. That is the practical reason browser-only code such as window, document, or localStorage access goes in onMounted.
If you know React, onMounted plus onUnmounted together cover what a useEffect with an empty dependency array and a cleanup function does. The difference is that Vue’s setup does not re-run on every render, so there is no dependency array to get wrong. Compare the component lifecycle with hooks.
What the video covers
Danny’s episode works through the Composition API hooks in a running app: the mounted pair, the activated pair used with <KeepAlive>, the updated pair, and registering several hooks of the same type in one component. It does not cover cleanup on unmount at length, the synchronous registration rule, or SSR behaviour. Those are carried above because they are where real bugs come from. Codevolution’s three-minute video in the “go deeper” links maps each Options API hook to its onX equivalent, which is handy if you are reading older code.
Where this fits
That completes the reactivity group. Next comes building interfaces from many components that pass data between them, starting with components and props.
Check yourself
Why does `document.querySelector('#chart')` return `null` at the top of `<script setup>` but find the element inside `onMounted`?
`<script setup>` runs when the instance is created, before Vue has rendered the template or inserted anything into the document, so the element does not exist yet. `onMounted` runs after the component's DOM has been created and inserted, so the element is there. In real code you would also prefer a template ref over a global query.
A component adds `window.addEventListener('resize', onResize)` in `onMounted`. What happens if it never removes it, given the component is shown and hidden ten times with `v-if`?
Each mount adds another listener, and none are removed on unmount, so after ten cycles ten copies of `onResize` run on every resize. Each one also keeps its component's state alive in memory. Calling `window.removeEventListener('resize', onResize)` in `onUnmounted` fixes it.
Why does this register nothing: `setTimeout(() => { onMounted(() => console.log('hi')) }, 0)`?
Lifecycle hooks attach themselves to the component instance that is currently running setup. By the time the timeout callback runs, setup has finished and there is no current instance, so Vue has nothing to attach the hook to and warns in development. Hooks have to be called synchronously during setup, directly or from a function, such as a composable, that setup calls.
You want to scroll a chat window to the bottom whenever a new message is added. Why is a watcher better than `onUpdated`?
`onUpdated` fires after every re-render of the component, including ones caused by unrelated state like a typing indicator, so the scroll would run far more often than intended. `watch(messages, scrollToBottom, { deep: true, flush: 'post' })` runs exactly when the messages change, after the DOM has been updated, so the new message is there to scroll to.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.