Reactivity

Learn how to handle state changes for head tags in Svelte.

Introduction

Unhead works in Svelte by attaching to the Svelte context. This allows you to manage head tags across your app with ease.

Svelte does not support reactivity outside of components, to support reactive tags requires slightly different syntax.

Using $effect

To make sure state changes will trigger an update to our tags, we need to initialise our head entry using useHead() and use the provided patch() function within a Svelte $effect.

<script lang="ts">

let title = $state('hello world')

const head = useHead()

$effect(() => {
  head.path({
    title,
  })
})

</script>

<button onclick={title = 'Updated title'}>update title</button>

While we could technically call useHead() within the $effect, this is the best practice to avoid unneeded memory allocations.

Did this page help you?