Suggest an editImprove this articleRefine the answer for “Can you use ref inside composition hooks?”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)**Yes,** `ref` can be used inside composition hooks (`onMounted`, `onUpdated`, `onUnmounted`, and others) - this is normal, officially supported practice. **Key point:** in the Composition API, access to DOM elements through `ref` is almost always done inside lifecycle hooks, most often in `onMounted()`.Shown above the full answer for quick recall.Answer (EN)Image**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** `ref` **is almost always done inside lifecycle hooks, most often in** `onMounted()`**.** --- ## Why does this work? Because: - `ref()` is declared inside `setup()` - 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 from `setup`, including `ref` --- ## 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) // null ``` This 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 existFor the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.