Vue interview

Reactivity

How Vue tracks dependencies with track and trigger, ref versus reactive, why destructuring a reactive object breaks it, computed and its lazy cache, shallowRef, nextTick and DOM update timing, and a writable computed.

From your Vue app, Directives, Reactivity, Computed note and the reactivity part of Important.

Know

  • Tracking: reactive is a Proxy, ref a getter and setter on .value (an object inside becomes reactive). Reads during a render, computed or watcher call track; writes call trigger, which marks computeds dirty, queues watchers and queues the re-render in a microtask.
  • ref versus reactive: ref works for any value, survives replacing .value and can be destructured from a returned object; reactive only takes objects and loses reactivity when replaced or destructured (use toRefs). The docs recommend ref as the default.
  • Computed: cached and lazy; a change marks it dirty, it recomputes only when read. No side effects in the getter. Writable with get/set; since 3.4 the getter receives the previous value.
  • shallowRef: tracks only .value; replace the value or call triggerRef. For large data from APIs or libraries.
  • Timing: state changes are synchronous, DOM updates are batched into a microtask; await nextTick() before reading the DOM.

Fact check of your notes

Gotcha· app.mount is called in main.ts

"Application renders on app.mount('#app') in app.vue": createApp(App) and app.mount('#app') live in the entry file, usually main.ts; App.vue is the root component being mounted.

Exercise

Exercise
  • Write the track and trigger functions and a 20-line reactive() from memory, and make an effect re-run when a property changes.
  • Destructure a reactive object, see the template stop updating, fix it with toRefs, then rewrite it with ref.

Be able to say

Be able to say· When do you use ref and when reactive?

"I use ref by default. It holds any value, stays reactive when I replace .value, and composables can return refs that callers destructure. reactive only takes objects and breaks when it's replaced or destructured, so I keep it for a group of related state I always use through the object, like a form. For big data I don't need tracked deeply, shallowRef."

Be able to say· How is a computed different from a method?

"A computed is cached: it tracks what it reads, marks itself dirty when that changes, and recomputes only when someone reads it again. A method in the template runs on every render. So derived data, like a filtered list, goes into a computed, side effects go into watchers, and the computed getter stays pure."

Your notes

Open in Notes

Nothing yet. Notes filed here show up on this page and the section overview.