·
2 min read

Vue Tip: Use Your Composables Synchronously

MH

Michael Hoffmann

@mokkapps

Vue Tip: Use Your Composables Synchronously Image

You should always call your composables synchronously in setup() hook or <script setup>. It would be best not to use await or Promise.all() when calling your composables. For example, the following code using the setup() hook is not recommended:

Component.vue
<script>
import { ref, watch, onMounted, onUnmounted } from 'vue'

export default {
  async setup() {
    const counter = ref(0)

    watch(counter, () => console.log(counter.value))

    // ✅ this lifecycle hook is called
    onMounted(() => console.log('Setup Hook: Mounted'))

    // ⌛ an async operation is started
    await new Promise((resolve) => {
      setTimeout(() => {
        console.log('Setup Hook: Resolve await')
        resolve()
      }, 1000)
    })

    // ☠️ this lifecycle hook is not called
    onUnmounted(() => console.log('Setup Hook: Unmounted'))

    // ⚠️ watcher works but is not automatically disposed
    // after the component is destroyed, which can cause a memory leak
    watch(counter, (newCounter) => {
      console.log('Setup Hook: Watcher', newCounter)
    })

    return { counter }
  },

  mounted() {
    console.log('Setup Hook: Mounted', this.count) // 0
  },
}
</script>

Vue must know the currently active component instance to register lifecycle hooks, watchers, and computed properties. If you call your composables asynchronously, Vue will not be able to determine the current active component instance and cannot register these features.

<script setup> is the only place to call composables after using await. After the async operation, the compiler automatically restores the active instance context for you.

Component.vue
<script setup>
import { ref, watch, onMounted, onUnmounted } from 'vue'

const counter = ref(0)

watch(counter, () => console.log(counter.value))

// ✅ this lifecycle hook is called
onMounted(() => console.log('Script Setup: Mounted'))

// the await statement
await new Promise((resolve) => {
  setTimeout(() => {
    console.log('Script Setup: Resolve await')
    resolve()
  }, 1000)
})

// ✅ this lifecycle hook is called
onUnmounted(() => console.log('Script Setup: Unmounted'))

// ✅ watcher works and is automatically disposed after the component is destroyed
watch(counter, (newCounter) => {
  console.log('Script Setup: Watcher', newCounter)
})
</script>
Only in <script setup> you can call your composables after using await. After the async operation, the compiler automatically restores the active instance context for you.

Recommendation

I suggest you always call your composables synchronously in both setup() hook and <script setup>. Sometimes, you can call them in lifecycle hooks like onMounted(). This will ensure that your composables are always called in the correct context and that Vue can register all the necessary features.

A good example is the useFetch composable to fetch data from an API:

useFetch.ts
import { ref } from 'vue'

export const useFetch = (url: string) => {
  const data = ref(null)
  const error = ref(null)

  fetch(url)
    .then((res) => res.json())
    .then((json) => (data.value = json))
    .catch((err) => (error.value = err))

  return { data, error }
}

You can call this composable synchronously in the setup() hook or <script setup>:

Component.vue
<script setup>
import { useFetch } from './useFetch.ts'

const { data, error } = useFetch('/api/data')
</script>

StackBlitz

Try it yourself in the following StackBlitz project:

Further Reading

Async with Composition API is an excellent article by Anthony Fu that explains this topic in more detail.

If you liked this Vue tip, follow me on BlueSky to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter :

I will never share any of your personal data. You can unsubscribe at any time.