Tech Interview RoomStudy guides

Vue.js

How does Vue 3 reactivity work? ref vs reactive.

Intermediate · 2 min read · Lesson 4 of 12 in Vue.js

Vue 3 tracks dependencies at runtime using JavaScript Proxies (for reactive) and getter/setter objects (for ref).

Tracking and triggering

  1. When an effect runs (a component's render, a computed, a watchEffect), every reactive property it reads is recorded as a dependency (track).
  2. When a property is written, Vue re-runs exactly the effects that depend on it (trigger). Component updates are batched and applied asynchronously in the next microtask; await nextTick() waits for the DOM to update.

ref

  • Wraps any value (including primitives) in an object with a .value property.
  • Objects inside a ref are made deeply reactive automatically.
  • Can be reassigned (list.value = newList), passed around and destructured from composables safely.
  • Auto-unwrapped in templates.

reactive

  • Makes an object deeply reactive through a Proxy; no .value.
  • Cannot hold primitives, and cannot be replaced (state = {...} breaks reactivity).
  • Destructuring loses reactivity: const { count } = state copies a plain number. Use toRefs(state) to destructure safely.

The Vue docs recommend ref as the default because it avoids these pitfalls.

Opt-outs

shallowRef / shallowReactive track only the top level (good for large immutable data); markRaw excludes an object (such as a chart instance) from reactivity; readonly creates a read-only proxy.

Example

js
import { ref, reactive, toRefs, watchEffect, nextTick } from 'vue';

const count = ref(0);
const state = reactive({ user: { name: 'Asha' }, tags: [] });

watchEffect(() => {
  console.log(`count=${count.value}, user=${state.user.name}`);  // tracks both
});

count.value++;                 // the effect re-runs
state.user.name = 'Ravi';      // nested change: re-runs (deep reactivity)

let { tags } = state;          // still reactive: tags is the nested proxy
const { user } = toRefs(state); // user is a ref linked to state.user

async function addTag(t) {
  state.tags.push(t);
  await nextTick();            // DOM now shows the new tag
}

Follow-up questions interviewers ask

Try answering each one before you open it.

How is Vue 3 reactivity better than Vue 2's?

Vue 2 used Object.defineProperty on existing keys, so it could not detect new properties or array index assignment (arr[0] = x) and needed Vue.set. Proxies intercept all operations, including additions, deletions, Map and Set, and only wrap nested objects lazily when they are accessed, which is faster for large data.