--- title: Vue Reactivity and Async Context description: Learn how to effectively use Vue's reactivity with Unhead for head tag management, and manage async context in your components. navigation: title: 'Context & Reactivity' --- **Quick Answer:** In Nuxt, pass refs and computed values directly to `useHead()` or `useSeoMeta()`. Reactivity is automatic. Use `injectHead()` when you need the head instance 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 Nuxt? When using any of the Unhead composables like [`useHead()`](/docs/head/api/composables/use-head){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 is attached to the Nuxt instance. When we call `useHead()`{lang="ts"}, it accesses the global Nuxt instance and uses the Unhead instance from it. ### 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. ### What Is the Difference Between Client and Server Reactivity? 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 '#imports' 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. ### Can I 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. ### How Do I Use effectScope for Async Operations? The `effectScope()`{lang="ts"} API allows you to re-run a code block using the same component context: ```vue ``` ### When Should I Use injectHead? The `injectHead()`{lang="ts"} 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. ### What Is the Best Way to Handle Async Head Updates? 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. #### How Do I Use Head with Pinia? You can also use this pattern with more complex state management: ```vue ``` ## 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 Call 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 Do 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 ``` ## Advanced Uses ### How Do I Create Dynamic SEO Meta Tags? ```ts 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 // https://unhead.unjs.io/docs/head/api/composables/use-seo-meta 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 Async Context Automatically? 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).