All posts

Practical Vue 3 Composition API Patterns

AI App Development240 words · 2 min read

The short version

Practical Vue 3 Composition API conventions: default to ref, derive values in computed, keep watch dependencies explicit, and guarantee cleanup inside every composable.

1. Default to ref for All Reactive State

Teams often debate when to pick ref versus reactive. After fixing enough subtle reactivity bugs, the cleanest team rule is simple: default to ref everywhere.

JavaScript
import { ref } from 'vue'

const count = ref(0)
const user = ref({ name: 'Ank', role: 'developer' })

// Replacing an entire payload from an API stays clean
user.value = await fetchProfile()

reactive introduces two recurring footguns:

  • Destructuring breaks reactivity: const { name } = state drops tracking unless wrapped in toRefs.
  • No direct reassignment: refreshing an object from the server requires Object.assign or field-by-field mutation, which easily leaves stale keys behind.

2. Put Derived State in computed, Never in watch

If a value can be derived from existing reactive state, compute it instead of mirroring it into another ref inside a watch callback. computed is lazy, cached, and eliminates ordering glitches between dependent updates.

JavaScript
const visiblePosts = computed(() =>
  posts.value.filter(item => !item.hidden && item.lang === locale.value)
)

3. Prefer Explicit watch Over watchEffect

watch makes every dependency explicit during code review. watchEffect silently tracks every reactive property read synchronously inside its body, which makes it easy to trigger unexpected network calls months later when a branch changes.

JavaScript
watch([() => route.params.slug, locale], ([slug, lang]) => {
  loadArticle(slug, lang)
})

For async watchers, always pair them with an incrementing request token or AbortController so an older slow response cannot overwrite a newer navigation.

4. Every Composable Must Clean Up After Itself

If a useXxx() composable registers window listeners, IntersectionObserver instances, or timers, tear them down inside the same module with onBeforeUnmount or return an explicit dispose() hook. On heavy pages with editors, charts, or WebGL canvases, a single leaked listener or requestAnimationFrame loop compounds quickly across route transitions.

A saved version is open. Try again to read the latest content.

Was this useful?

If this post helped, you can buy me a coffee ☕

The next post, in your reader

Get new posts via RSS in Feedly, Reeder, or your preferred feed reader.

Subscribe via RSS