--- title: Vue Reactivity and Async Context description: 'Use refs, computed, and Pinia with useHead(). Handle async context in lifecycle hooks with injectHead() or effectScope().' navigation: title: 'Context & Reactivity' --- **Quick Answer:** In Vue, pass refs and computed values directly to `useHead()`. Changes are tracked automatically. Use `injectHead()` in composables outside components. ## Introduction Unhead integrates seamlessly with Vue's reactivity system, allowing you to create dynamic and responsive head tags that automatically update when your data changes. This guide explains how to effectively manage reactive head tags and handle asynchronous operations in your Vue applications. ## How Does Reactivity Work in Unhead? When using any of the Unhead composables like `useHead()`{lang="ts"}, full reactivity is provided out of the box. All values support Vue's reactivity system, meaning your head tags will automatically update when reactive data changes. Behind the scenes, Unhead uses Vue's provide/inject system for head instance management. When we call `useHead()`{lang="ts"}, it uses the Vue [inject](https://vuejs.org/api/composition-api-dependency-injection.html#inject) function to get the Unhead instance attached to the Vue application: ```ts import { headSymbol } from '@unhead/vue' import { inject } from 'vue' function useHead(input) { const head = inject(headSymbol) head.push(input) } ``` ### How Does Component Lifecycle Affect Head Tags? Unhead integrates automatically with Vue's component lifecycle: - When a component is unmounted, any head entries created by that component are automatically removed - When a component is deactivated with keep-alive, its entries will be deactivated - When a component is activated with keep-alive, its entries will be reactivated This ensures your head tags stay in sync with your component's visibility state and prevents memory leaks when components are destroyed. ### How Does Reactivity Differ Between Client and Server? Reactivity behaves differently depending on the rendering context: - **Server-Side Rendering (SSR)**: Values are resolved only when the tags are being rendered, usually after the app has finished rendering. - **Client-Side Rendering (CSR)**: Any ref changes trigger a DOM update, making the head tags reactive after hydration. ## What Reactive Values Can I Use? Unhead works with all Vue reactive primitives: ```ts import { useHead } from '@unhead/vue' import { computed, ref } from 'vue' // Create reactive state const title = ref('My Site') const description = ref('Welcome to my website') // Use reactive values in head tags useHead({ // Direct ref title, meta: [ // Computed getter (recommended for derived values) { name: 'description', content: () => description.value }, // Using refs directly in objects { property: 'og:title', content: title } ], // Computed ref link: [computed(() => ({ rel: 'canonical', href: `https://example.com/products/${product.value.name}` }))] }) ``` ## How Do I Handle Async Context? The `inject()`{lang="ts"} function keeps track of your Vue component instance, but after async operations within lifecycle hooks or nested functions, Vue can lose track of this context. ```vue ``` When trying to inject once Vue has lost the context, you'll receive an error from Unhead: ::warning useHead() was called without provide context. :: Let's explore several solutions to handle this problem effectively. ### Solution 1: Use Top Level Await Vue's script setup handles async operations through [compile-time transforms](https://github.com/vuejs/rfcs/blob/master/active-rfcs/0040-script-setup.md#top-level-await) that preserve the component instance context. The Vue team devised an elegant solution for maintaining async context through these script setup transforms. At the top level of script setup, context is automatically preserved: ```vue ``` This is the simplest and most effective way to handle async operations in Vue. For a deeper understanding of how async context evolved in Vue's Composition API, check out Anthony Fu's [detailed exploration](https://antfu.me/posts/async-with-composition-api) of the topic. ### Solution 2: Using `effectScope()`{lang="ts"} The `effectScope()`{lang="ts"} API allows you to re-run a code block using the same component context: ```vue ``` ### Solution 3: Using `injectHead()`{lang="ts"} The `injectHead()` function lets us grab a reference to Unhead's instance before any async operations occur: ```vue ``` The key idea is that `injectHead()`{lang="ts"} should be called at the top level of your component, before any async operations. ### Solution 4: Using Reactive State (Recommended) The most elegant way to handle async head updates is to combine reactive state with `useHead()`{lang="ts"}: ```vue ``` This reactive state pattern aligns well with Vue's Composition API design and often results in cleaner, more maintainable code. #### Using with Pinia Store You can also use this pattern with more complex state management: ```vue ``` ## What Are the Best Practices? ### Should I Use Refs or Computed Getters? For the best performance and clarity, prefer direct refs and computed getters: ```ts // ✅ Good approach const title = ref('Product Page') const product = ref({ name: 'Widget' }) useHead({ // Direct ref title, // Computed getter meta: [ { property: 'og:title', content: () => `${product.value.name} - ${title.value}` } ] }) ``` ### Can I Use useHead Inside a Watcher? Avoid `useHead()`{lang="ts"} calls in watchers, as this creates new entries on each update: ```ts // ❌ Bad approach: Creates multiple entries watch(title, (newTitle) => { useHead({ title: newTitle }) }) // ✅ Good approach: Updates existing entry useHead({ title // ref value updates automatically }) ``` ### How Can I Optimize Frequent Component Mounts? When components are frequently mounted and unmounted, consider using Vue's built-in mechanisms like `v-if`/`v-show` or `` to optimize head tag management: ```vue // Using keep-alive allows Unhead to optimize head updates ``` ## What Are Some Advanced Use Cases? ### How Do I Create Dynamic SEO Meta Tags? ```ts import { useSeoMeta } from '@unhead/vue' import { computed, ref } from 'vue' import { useRoute } from 'vue-router' export default { setup() { const route = useRoute() const product = ref(null) // Fetch data based on route fetchProduct(route.params.id).then((data) => { product.value = data }) // SEO tags update automatically when product data is loaded useSeoMeta({ title: () => product.value?.name || 'Loading...', description: () => product.value?.description || '', ogImage: () => product.value?.image || '/default.jpg', }) } } ``` ### Can I Use Multiple useHead Calls? You can use multiple `useHead()`{lang="ts"} calls in different components, and Unhead will handle merging them correctly: ```ts // BaseLayout.vue useHead({ titleTemplate: '%s | My Site', meta: [ { name: 'theme-color', content: '#ff0000' } ] }) // ProductPage.vue useHead({ title: product.name, meta: [ { name: 'description', content: product.description } ] }) ``` ## Does Nuxt Handle This Differently? When using Nuxt, you don't need to worry about managing async context for head updates. This is because Nuxt attaches Unhead directly to the Nuxt application instance which is globally accessible regardless of the async operation. This allows you to use `useHead()`{lang="ts"} anywhere in your Nuxt application, including plugins, middleware, and layouts without worrying about context. ::tip If you're using Nuxt, async context management is handled automatically by the framework, so you can focus on the reactive aspects of your head tags. :: ## How Does Unhead Work Under the Hood? Under the hood, Unhead in Vue: 1. Uses Vue's provide/inject system for head instance management 2. Leverages `watchEffect` to track reactive dependencies 3. Integrates with Vue's component lifecycle hooks 4. Uses Vue's reactive resolver to unwrap refs and computed values This implementation ensures seamless integration with Vue's reactivity system while maintaining performance and proper cleanup. If you're interested in the technical details of Vue's script setup implementation, check out the [Script Setup RFC](https://github.com/vuejs/rfcs/blob/master/active-rfcs/0040-script-setup.md#top-level-await).