Build reusable logic with the Composition API — useXxx pattern, ref(), reactive(), computed(), watchEffect(), and onMounted()
0 / 5 completed
1 / 5
What is a Vue 3 composable and how does it differ from a mixin?
Composables: are plain TypeScript functions prefixed with use (e.g. useMousePosition()) that call ref(), computed(), watch() etc. They return reactive state and methods. Unlike mixins, their sources are explicit and they do not pollute the component namespace or cause property collisions.
2 / 5
What is the difference between ref() and reactive() in Vue 3?
ref() vs reactive():ref(0) returns { value: 0 } — access via .value in script, auto-unwrapped in templates. reactive({ count: 0 }) returns a Proxy you access directly. Primitives require ref() because proxies cannot intercept primitive assignments. Destructuring a reactive object loses reactivity; use toRefs() to preserve it.
3 / 5
How does watchEffect() differ from watch() in Vue 3?
watchEffect(): runs its callback immediately, collecting reactive dependencies accessed during execution, then re-runs whenever they change — similar to how computed() works but for side effects. watch() lazily observes explicit sources. Use watchEffect for data fetching that depends on multiple refs; use watch when you need the previous value.
4 / 5
What does computed() return in Vue 3's Composition API?
computed(): returns a ComputedRef — a readonly ref by default. It caches its result and only recalculates when reactive dependencies change. Pass a getter/setter object for a writable computed: computed({ get: () => ..., set: (v) => ... }). In templates, .value is auto-unwrapped.
5 / 5
In Vue 3, when should a composable call onMounted() vs running code directly in its body?
Lifecycle hooks in composables: Code in a composable's body runs synchronously during setup() — including on the server in SSR, where no DOM exists. DOM-dependent code (attaching event listeners, reading window, etc.) must go inside onMounted(). Use onUnmounted() to clean up listeners registered in onMounted().