Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 87 ยท Reactivity Fundamentals

Reactivity Pitfalls

Avoid the classic Vue 3 reactivity bugs - lost reactivity when destructuring, replacing reactive objects, mutating props, identity surprises, non-reactive values and debugging with onTrack.

Reactivity in Vue 3 is reliable, but it is not magic. It works through proxies and tracked reads, so it only works where Vue can see those reads and writes. Most "Vue is not updating" bugs come down to a short list of causes, and once you know them you can spot them in seconds.

This lesson walks through each one with a runnable example and the fix. It assumes you know ref, reactive, computed and the mechanism from How Reactivity Works.

flowchart TD
    S["Reactive state: a proxy"] -->|"read a property into a variable"| P["Plain copy, not tracked"]
    S -->|"toRefs or toRef"| R["Ref linked to the property"]
    S -->|"reassign the variable that held it"| X["Old proxy is still what the template uses"]
    S -->|"Object.assign or property writes"| OK["Tracked update"]

Reading a value out of a proxy gives you a copy; keeping the proxy, or a ref linked to it, keeps the connection.

Pitfall 1: destructuring reactive state

Reading a primitive out of a reactive object copies it. The new variable is an ordinary number or string, and it has no link to the proxy any more.

JavaScript
const state = reactive({ count: 0 });
const { count } = state;   // count is the number 0, forever
state.count++;             // state.count is 1, count is still 0

The same happens with function parameters (function show({ count }) {} called with state) and with let name = state.name. The fix is toRefs (all properties) or toRef (one property), which create refs that read and write the original property.

Destructuring copies, toRefs keeps the link

After one click, state.count and the toRefs value show 1, while the destructured copy still shows 0. The message line confirms it from inside setup.

Props have the same trap. Destructuring props at the top of setup() loses reactivity; use toRefs(props), or read props.x inside computeds and watchers. (Vue 3.5 with <script setup> can compile a destructured props declaration reactively, but that is a compiler feature, not something plain JavaScript gives you.)

Pitfall 2: replacing a reactive object

A reactive object is a proxy, and the template or a computed holds on to that proxy. If you assign a new object to the variable, the old proxy is still what everyone else points at.

JavaScript
let box = reactive({ n: 1 });
box = reactive({ n: 99 });   // the screen still uses the first proxy

You have two safe options:

  • Keep a ref and replace its value: form.value = { name: "Grace" }. Everything that read form.value updates.
  • Keep the same reactive object and change its contents: Object.assign(box, { n: 99 }), or set properties one by one.

Declare reactive variables with const; if you ever want to write let, you probably want a ref.

Pitfall 3: arrays by index (and what changed since Vue 2)

If you learned Vue 2, you may remember that arr[1] = "x" and arr.length = 0 were not detected. In Vue 3 both are tracked, because proxies see every write. You do not need Vue.set or splice tricks any more. The real array pitfalls in Vue 3 are the same as for objects: replacing a reactive array variable with a new array (use a ref, or arr.splice(0, arr.length, ...next)), and destructuring elements into copies.

Pitfall 4: identity is different through a proxy

A reactive proxy is not the same object as the one it wraps. That is correct, and occasionally surprising:

JavaScript
const raw = { id: 7 };
const items = reactive([raw]);

items[0] === raw;           // false: items[0] is a proxy of raw
toRaw(items[0]) === raw;    // true

This matters when you compare objects with ===, use them as Map or Set keys, or pass them to a library that stores references. Compare ids instead of objects, or call toRaw when you truly need the original. (For includes, indexOf and lastIndexOf on a reactive array, Vue searches with both the raw and the proxied value, so items.includes(raw) is true.)

Replacing, mutating and identity

Press the buttons one at a time. Replacing the ref value updates the name. Reassigning the reactive variable leaves box.n at 1 on screen, even though the variable now holds 99. Object.assign updates the live object, and the index assignment shows a, B, c. The identity check prints false, true, true, false, true, true in that order.

Pitfall 5: mutating props

Props flow one way, from parent to child. In a child component, reassigning a prop (props.count++) does nothing useful: Vue makes the props object read-only and prints a warning in development builds. The sneakier version is mutating a nested object that came in as a prop:

JavaScript
props.user.name = "Changed by the child"; // no warning, but it edits the parent's data

That works silently, because the object is shared, but it makes data flow impossible to follow: you cannot tell from the parent why its state changed. Instead, have the child emit an event and let the parent update its own state, or copy the prop into local state when the child needs its own editable version. The Props and Events and emits lessons cover the patterns in detail.

Pitfall 6: values Vue cannot see

Reactivity only covers reads and writes that go through a ref or a reactive proxy. These are invisible to it:

  • Plain variables. let total = 0 in setup() and total += 1 changes the variable, but nothing re-renders. Make it a ref.
  • Non-reactive inputs to a computed, such as Date.now(), Math.random() or window.innerWidth. The computed caches its first result forever (see Computed Properties).
  • Objects opted out on purpose with markRaw, or frozen with Object.freeze. Changes inside them are not tracked.
  • Writes that bypass the proxy, such as modifying the raw object returned by toRaw, or a third-party library mutating your data behind Vue's back.
  • Work after an await in watchEffect, which is no longer tracked (see Watchers).

A good first question for any stale screen is: "Is the value I changed a ref, or a property read through a reactive proxy?"

Debugging reactivity

When you cannot tell why an effect runs, or why it does not, Vue has development-only hooks. A computed, a watch or a watchEffect accepts onTrack and onTrigger options:

JavaScript
watchEffect(
  () => {
    console.log("total", state.price * state.qty);
  },
  {
    onTrack(event) {
      console.log("now depends on", event.key);
    },
    onTrigger(event) {
      console.log("re-run because", event.key, "changed", event.oldValue, "->", event.newValue);
    }
  }
);

onTrack fires each time a dependency is recorded, and onTrigger fires when a change schedules the effect. Both only run in development builds of Vue: the minified production build used by the examples on this site skips them, so run this code in a project created with create-vue and watch the browser console. Other cheap checks work everywhere: isRef, isReactive, isProxy and toRaw tell you what kind of value you really hold. Vue DevTools shows the live state of components and refs; Debugging Vue covers it in detail.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this give you? const state = reactive({ n: 0 }); const { n } = state; state.n++;

    Reading a primitive out of a reactive object copies the value. Use toRefs(state) or toRef(state, 'n') to get a ref that stays linked.
  2. 2. Which approach correctly replaces all the data of a reactive object so the template updates?

    The template holds the original proxy. Changing its contents with Object.assign keeps that proxy, while reassigning the variable creates a new object nobody is watching. A ref and box.value = ... is the other safe option.
  3. 3. In Vue 3, what is true about changing an array item with list[1] = 'B' on a reactive array?

    The index limitation belonged to Vue 2. Vue 3 proxies intercept index writes and length changes, so they trigger updates.
  4. 4. A child component does props.user.name = 'x', where user is an object passed down by the parent. What happens?

    Only the props object itself is read-only (shallowly). A nested object is shared, so the mutation reaches the parent. Emit an event or copy the data instead.
  5. 5. Why won't onTrack and onTrigger print anything in a TryIt that loads the production Vue build?

    Debug hooks are compiled out of the minified production build to keep it small and fast. Use a development build (for example a Vite dev server) when you need them.

Summary

  • Destructuring a reactive object copies primitive values; use toRefs or toRef to keep the link.
  • Never reassign a variable holding a reactive object; use a ref and replace .value, or Object.assign into the same object.
  • In Vue 3 arrays are tracked by index and length; replacing the array variable is the pitfall.
  • A proxy is not equal to its raw object: compare ids, or use toRaw.
  • Do not mutate props, including nested objects; emit events or copy to local state.
  • Plain variables, non-reactive inputs, markRaw, frozen objects and writes through raw objects are invisible to Vue.
  • Use onTrack, onTrigger (development builds only), isRef, isReactive, toRaw and DevTools to investigate.

You now have a solid foundation in reactivity. Next, use it to build interactive forms with Two-Way Binding with v-model.