Practical Vue 3 Composition API Patterns
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.
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 } = statedrops tracking unless wrapped intoRefs. - No direct reassignment: refreshing an object from the server requires
Object.assignor 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.
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.
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.
The next post, in your reader
Get new posts via RSS in Feedly, Reeder, or your preferred feed reader.