Can you use ref inside composition hooks?
Yes, ref can be used inside composition hooks (onMounted, onUpdated, onUnmounted and others) - this is exactly normal, officially supported practice.
Moreover:
In the Composition API, access to DOM elements through
refis almost always done inside lifecycle hooks, most often inonMounted().
Why does this work?
Because:
ref()is declared insidesetup()- its value (
ref.value) gets bound to the DOM element only after the component is mounted - composition hooks (
onMounted,onUpdated, etc.) can use any variables fromsetup, includingref
Example: using ref inside onMounted()
vue
<template>
<input ref="inputEl" />
</template>
<script setup>
import { ref, onMounted } from 'vue'
const inputEl = ref(null)
onMounted(() => {
inputEl.value.focus() // this works!
})
</script>Example: using ref inside onUpdated()
vue
<script setup>
import { ref, onUpdated } from 'vue'
const box = ref(null)
const count = ref(0)
onUpdated(() => {
console.log("Size after update:", box.value.clientWidth)
})
</script>Which hooks are most often used with ref?
| Hook | What it's used for with ref |
|---|---|
onMounted() | accessing the DOM for the first time |
onUpdated() | measurements after an update |
onBeforeUnmount() | unsubscribing from events if they were attached to the ref element |
onUnmounted() | final cleanup |
onActivated() | restoring the ref after keep-alive |
Important to remember
1. Inside setup(), ref does not contain the DOM element yet
js
console.log(inputEl.value) // nullThis is normal.
2. You cannot access ref in setup() or onBeforeMount()
The element does not exist in the DOM yet.
3. In onMounted(), ref is guaranteed to exist
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.