Vue.js course Β· Module 3: Reactivity

Debugging Reactivity

5 min read Β·
In this lesson6

Even the best NOVA LAB engineers sometimes need to debug their systems. Learn the tools for debugging reactivity.

"The panel does not refresh" is the most common entry in the station's fault log. The cause almost always lies in the data: the value turns out to be a plain object instead of a Proxy, or it lost its connection after destructuring. Before you start rewriting the component, check what you are really working with - Vue has a set of diagnostic testers for that.

isRef() and isReactive()

isRef() returns true when the value is a ref. isReactive() checks whether an object is a Proxy created by reactive() or shallowReactive(). Both functions return a boolean:

import { ref, reactive, isRef, isReactive } from 'vue'

const powerLevel = ref(0)
const reactor = reactive({ name: 'Plasma Core Alpha' })
const plainConfig = { mode: 'safe' }

console.log(isRef(powerLevel))       // true
console.log(isRef(reactor))     // false
console.log(isReactive(reactor)) // true
console.log(isReactive(powerLevel))   // false
console.log(isReactive(plainConfig)) // false

A ref is not a Proxy, which is why isReactive(powerLevel) gives false. An object stored inside a ref already is one: isReactive(ref({}).value) returns true. Related testers are isProxy(), which recognizes any Vue Proxy, including read-only ones, and isReadonly().

unref() - Safe Reading Unpacking

unref(x) is shorthand for isRef(x) ? x.value : x. It lets you write a function that accepts both a ref and a plain value:

import { ref, unref } from 'vue'

const temperature = ref(2500)
const plainReading = 1500

// unref returns .value for ref, or the value directly
console.log(unref(temperature))      // 2500
console.log(unref(plainReading)) // 1500

// Useful in universal functions
function convertToFahrenheit(kelvin) {
  return (unref(kelvin) - 273.15) * 9/5 + 32
}

convertToFahrenheit(temperature)      // 4040.3299999999995 (about 4040.33)
convertToFahrenheit(plainReading) // 2240.33

The long tail after the decimal point is ordinary JavaScript floating-point arithmetic, not Vue's fault - for display use toFixed(2). Since Vue 3.3 there is also toValue(), which works like unref() and additionally calls getters passed to it.

toRaw() - Raw Sensor Object

toRaw() returns the original object hidden behind the Proxy. It is an escape hatch: reads through it are not tracked, and writes do not refresh the view.

import { reactive, toRaw } from 'vue'

const reactor = reactive({
  name: 'Plasma Core Alpha',
  temperature: 2500
})

const rawReactor = toRaw(reactor)
console.log(rawReactor) // Original object without Proxy

// Useful for:
// - Comparing objects
// - Passing to APIs that do not accept a Proxy (e.g. structuredClone)
// - External libraries

JSON.stringify() handles a Proxy without trouble, but structuredClone() or postMessage() throw a DataCloneError - give them toRaw(reactor) instead. The docs advise against keeping a persistent reference to the raw object, because it is easy to make changes the panel never notices.

markRaw() - Disabling Reactivity

markRaw() marks an object so that Vue never turns it into a Proxy, and returns the same object:

import { reactive, markRaw } from 'vue'

const externalSensorLibrary = markRaw({
  hardwareInterface: new Map(),
  calibrate() { /* ... */ }
})

const state = reactive({
  sensor: externalSensorLibrary // Will not be reactive
})

// Useful for:
// - Hardware libraries (sensor drivers, hardware interfaces)
// - Large immutable data from the NOVA LAB database
// - Vue component objects

isReactive(state.sensor) returns false, and state.sensor is exactly the same object as externalSensorLibrary. A Proxy can even break some library classes: a method that reaches for a private field written with a hash, for example #points, throws a TypeError in that case. markRaw prevents this. Note: the mark applies only to the object itself, not to its nested fields.

Debugging with watch

watch(source, callback) calls a function with the new and the old value after every change of the source, and the immediate: true option runs it right away. We will cover watchers in module 4, but they can already help with the investigation:

import { ref, watch } from 'vue'

const count = ref(0)

watch(count, (newValue, oldValue) => {
  console.log(`count changed: ${oldValue} β†’ ${newValue}`)
  console.trace() // Stack trace - where did the change come from?
}, { immediate: true })

The first entry is count changed: undefined β†’ 0, because at the start there is no old value yet. console.trace() prints the call stack, so you can see which function changed the reading. In development mode Vue also offers the onTrack and onTrigger options for watchers and computed properties, and the onRenderTracked and onRenderTriggered hooks.

Vue DevTools

Vue DevTools is a browser extension, also available as a Vite plugin. In Vue DevTools you can:

  • See all reactive data
  • Track changes in real time
  • Edit values live
  • See the dependency tree

The Components tab shows the component tree with its state, the Timeline records events and rendering times, and the Graph tab shows the reactive dependencies of the selected component. Install it on day one - it will save you hours of guessing. In the next lesson you will assemble all the tools you have learned into practical panels.

Remember: before you take the reactor apart, check it with a tester - isRef and isReactive tell you whether the wire is connected at all.

Code for this lesson: App.vue
<script setup>
import { ref, reactive, shallowRef, shallowReactive, readonly, triggerRef } from 'vue'

// Advanced reactivity - shallow and readonly
// NOVA LAB mission data protection system

// shallowRef - reactivity only at .value level
const missionData = shallowRef({
  id: 'MISSION-2087',
  crew: ['Chen', 'Rodriguez', 'Kim'],
  objectives: {
    primary: 'Establish Mars base',
    secondary: 'Collect samples'
  }
})

// shallowReactive - reactivity only at the first level
const missionStatus = shallowReactive({
  name: 'Mars Colony Alpha',
  phase: 'DEPLOYMENT',
  timeline: {
    start: '2087-03-15',
    current: '2087-06-20',
    estimated_end: '2087-12-31'
  },
  modules: {
    habitation: { status: 'ACTIVE', progress: 75 },
    power: { status: 'ACTIVE', progress: 90 },
    lifesupport: { status: 'TESTING', progress: 60 }
  }
})

// readonly - read-only
const criticalParameters = readonly(reactive({
  maxCrewSize: 12,
  minOxygen: 21,
  maxRadiation: 100,
  safetyProtocols: {
    emergency: 'AUTO_SHUTDOWN',
    backup: 'REDUNDANT_SYSTEMS'
  }
}))

// Normal ref example for comparison
const normalMissionData = ref({
  id: 'MISSION-2087',
  crew: ['Chen', 'Rodriguez', 'Kim']
})

// Demonstration of shallowRef
function modifyShallowRef() {
  // This will NOT work - change to a deeply nested property
  missionData.value.objectives.primary = 'Build greenhouse'
  console.log("Modified nested property, but UI won't update automatically")

  // We must manually call triggerRef
  // triggerRef(missionData)
}

function replaceShallowRef() {
  // This WILL work - replacing the entire .value
  missionData.value = {
    ...missionData.value,
    objectives: {
      primary: 'Build greenhouse',
      secondary: 'Test farming systems'
    }
  }
}

function forceUpdateShallowRef() {
  // Modification of nested property
  missionData.value.crew.push('Jackson')
  // Manually forcing update
  triggerRef(missionData)
}

// Demonstration of shallowReactive
function modifyShallowReactive() {
  // This WILL work - change at the first level
  missionStatus.phase = 'OPERATIONAL'
}

function modifyDeepShallowReactive() {
  // This will NOT work automatically - change deeper
  missionStatus.modules.habitation.progress = 100
  console.log("Modified deep property, UI won't update")
}

function replaceNestedShallowReactive() {
  // This WILL work - replacing the object at the first level
  missionStatus.modules = {
    ...missionStatus.modules,
    habitation: { status: 'COMPLETE', progress: 100 }
  }
}

// Demonstration of readonly
function tryModifyReadonly() {
  try {
    // This will NOT work - readonly blocks modifications
    criticalParameters.maxCrewSize = 20
  } catch (e) {
    console.warn('Cannot modify readonly object')
  }
}

// Counters for demonstration
const shallowRefCounter = ref(0)
const shallowReactiveCounter = ref(0)
const readonlyCounter = ref(0)
</script>

<template>
  <div class="advanced-reactivity">
    <div class="header">
      <h1>DATA PROTECTION SYSTEM - NOVA LAB</h1>
      <p class="subtitle">shallowRef(), shallowReactive(), readonly(), triggerRef()</p>
    </div>

    <!-- shallowRef Demo -->
    <div class="demo-section">
      <h2>shallowRef() - Shallow reactivity</h2>
      <div class="demo-grid">
        <div class="info-card">
          <h3>Characteristics</h3>
          <ul>
            <li>Reactive only at the <code>.value</code> level</li>
            <li>Changes to deeply nested properties do NOT trigger updates</li>
            <li>Use <code>triggerRef()</code> to force an update</li>
            <li>More efficient for large objects</li>
          </ul>
        </div>

        <div class="data-card">
          <h3>Mission data (shallowRef)</h3>
          <pre>{{ JSON.stringify(missionData, null, 2) }}</pre>

          <div class="controls">
            <button @click="modifyShallowRef(); shallowRefCounter++" class="btn btn-warning">
              Modify nested (won't work)
            </button>
            <button @click="replaceShallowRef(); shallowRefCounter++" class="btn btn-success">
              Replace .value (will work)
            </button>
            <button @click="forceUpdateShallowRef(); shallowRefCounter++" class="btn btn-info">
              Force update (triggerRef)
            </button>
          </div>

          <div class="counter">
            Number of actions: {{ shallowRefCounter }}
          </div>
        </div>
      </div>

      <div class="code-example">
        <h4>Code example:</h4>
        <pre>const data = shallowRef({ nested: { value: 1 } })

// Won't trigger UI update
data.value.nested.value = 2

// Will trigger UI update
data.value = { nested: { value: 2 } }

// Force update after modification
data.value.nested.value = 2
triggerRef(data)</pre>
      </div>
    </div>

    <!-- shallowReactive Demo -->
    <div class="demo-section">
      <h2>shallowReactive() - Shallow reactivity for objects</h2>
      <div class="demo-grid">
        <div class="info-card">
          <h3>Characteristics</h3>
          <ul>
            <li>Only first-level properties are reactive</li>
            <li>Nested objects are NOT reactive</li>
            <li>Nested objects must be replaced entirely</li>
            <li>Efficient for flat structures</li>
          </ul>
        </div>

        <div class="data-card">
          <h3>Mission status (shallowReactive)</h3>
          <div class="status-display">
            <p><strong>Name:</strong> {{ missionStatus.name }}</p>
            <p><strong>Phase:</strong>
              <span class="phase-badge">{{ missionStatus.phase }}</span>
            </p>
            <p><strong>Timeline:</strong> {{ missionStatus.timeline.current }}</p>

            <div class="modules-grid">
              <div
                v-for="(module, key) in missionStatus.modules"
                :key="key"
                class="module-card"
              >
                <div class="module-name">{{ key }}</div>
                <div class="module-status">{{ module.status }}</div>
                <div class="progress-bar">
                  <div class="progress-fill" :style="{ width: module.progress + '%' }">
                    {{ module.progress }}%
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="controls">
            <button @click="modifyShallowReactive(); shallowReactiveCounter++" class="btn btn-success">
              Change phase (1st level)
            </button>
            <button @click="modifyDeepShallowReactive(); shallowReactiveCounter++" class="btn btn-warning">
              Change progress (deep)
            </button>
            <button @click="replaceNestedShallowReactive(); shallowReactiveCounter++" class="btn btn-success">
              Replace module
            </button>
          </div>

          <div class="counter">
            Number of actions: {{ shallowReactiveCounter }}
          </div>
        </div>
      </div>

      <div class="code-example">
        <h4>Code example:</h4>
        <pre>const state = shallowReactive({
  count: 0,
  nested: { value: 1 }
})

// Will work - first level
state.count = 1

// Won't work - nested
state.nested.value = 2

// Will work - replacement
state.nested = { value: 2 }</pre>
      </div>
    </div>

    <!-- readonly Demo -->
    <div class="demo-section">
      <h2>readonly() - Read-only data</h2>
      <div class="demo-grid">
        <div class="info-card">
          <h3>Characteristics</h3>
          <ul>
            <li>Complete protection against modification</li>
            <li>Ideal for constant configurations</li>
            <li>Prevents accidental changes</li>
            <li>Displays warnings in dev mode</li>
          </ul>
        </div>

        <div class="data-card">
          <h3>Critical parameters (readonly)</h3>
          <div class="critical-params">
            <div class="param-item">
              <span class="param-label">Max crew:</span>
              <span class="param-value">{{ criticalParameters.maxCrewSize }}</span>
            </div>
            <div class="param-item">
              <span class="param-label">Min oxygen (%):</span>
              <span class="param-value">{{ criticalParameters.minOxygen }}</span>
            </div>
            <div class="param-item">
              <span class="param-label">Max radiation:</span>
              <span class="param-value">{{ criticalParameters.maxRadiation }} mSv</span>
            </div>
            <div class="param-item">
              <span class="param-label">Emergency protocol:</span>
              <span class="param-value">{{ criticalParameters.safetyProtocols.emergency }}</span>
            </div>
            <div class="param-item">
              <span class="param-label">System backup:</span>
              <span class="param-value">{{ criticalParameters.safetyProtocols.backup }}</span>
            </div>
          </div>

          <div class="controls">
            <button @click="tryModifyReadonly(); readonlyCounter++" class="btn btn-danger">
              Attempt modification (won't work)
            </button>
          </div>

          <div class="counter">
            Failed modification attempts: {{ readonlyCounter }}
          </div>

          <div class="warning-box">
            Critical parameters are protected from modification
          </div>
        </div>
      </div>

      <div class="code-example">
        <h4>Code example:</h4>
        <pre>const config = readonly(reactive({
  apiKey: 'secret',
  maxRetries: 3
}))

// Won't work - readonly
config.maxRetries = 5 // Warning in console

// We can only read
console.log(config.maxRetries) // 3</pre>
      </div>
    </div>

    <div class="info-box">
      <h3>When to use advanced functions?</h3>
      <div class="use-cases">
        <div class="use-case">
          <h4>shallowRef()</h4>
          <p>Large objects where you change the entire object at once, not individual properties</p>
        </div>
        <div class="use-case">
          <h4>shallowReactive()</h4>
          <p>Flat data structures with many properties at the first level</p>
        </div>
        <div class="use-case">
          <h4>readonly()</h4>
          <p>Configurations, constants, data that should not be modified</p>
        </div>
        <div class="use-case">
          <h4>triggerRef()</h4>
          <p>Manually forcing an update after modifying a shallowRef</p>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.advanced-reactivity {
  min-height: 100vh;
  background: #0a0e27;
  color: #e0e0e0;
  padding: 2rem;
  font-family: 'Courier New', monospace;
}

.header {
  text-align: center;
  margin-bottom: 2rem;
  border-bottom: 2px solid #00ff88;
  padding-bottom: 1rem;
}

.header h1 {
  color: #00ff88;
  font-size: 2rem;
  margin: 0;
  text-shadow: 0 0 10px #00ff88;
}

.subtitle {
  color: #00b4d8;
  margin: 0.5rem 0 0 0;
}

.demo-section {
  background: #1a1f3a;
  padding: 1.5rem;
  border-radius: 8px;
  border: 1px solid #00b4d8;
  margin-bottom: 2rem;
}

.demo-section h2 {
  color: #00ff88;
  margin-top: 0;
}

.demo-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
  gap: 1.5rem;
  margin-bottom: 1.5rem;
}

.info-card, .data-card {
  background: #0a0e27;
  padding: 1.5rem;
  border-radius: 6px;
}

.info-card h3, .data-card h3 {
  color: #00b4d8;
  margin-top: 0;
}

.info-card ul {
  list-style: none;
  padding: 0;
}

.info-card li {
  margin: 0.8rem 0;
  padding-left: 1.5rem;
  position: relative;
}

.info-card code {
  background: #1a1f3a;
  padding: 0.2rem 0.5rem;
  border-radius: 3px;
  color: #00ff88;
}

.data-card pre {
  background: #1a1f3a;
  padding: 1rem;
  border-radius: 4px;
  overflow-x: auto;
  font-size: 0.85rem;
  color: #00ff88;
}

.controls {
  display: flex;
  flex-direction: column;
  gap: 0.8rem;
  margin: 1rem 0;
}

.btn {
  padding: 0.8rem 1rem;
  font-size: 0.9rem;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: bold;
  transition: all 0.3s ease;
  font-family: 'Courier New', monospace;
  text-align: left;
}

.btn-success {
  background: linear-gradient(135deg, #00ff88, #00dd77);
  color: #0a0e27;
}

.btn-warning {
  background: linear-gradient(135deg, #ffaa00, #ff8800);
  color: #0a0e27;
}

.btn-danger {
  background: linear-gradient(135deg, #ff4444, #cc0000);
  color: white;
}

.btn-info {
  background: linear-gradient(135deg, #00b4d8, #0088cc);
  color: white;
}

.btn:hover {
  transform: scale(1.02);
  box-shadow: 0 0 15px currentColor;
}

.counter {
  background: #1a1f3a;
  padding: 0.8rem;
  border-radius: 4px;
  text-align: center;
  color: #00ff88;
  font-weight: bold;
  margin-top: 1rem;
}

.status-display p {
  margin: 0.5rem 0;
  color: #ccc;
}

.phase-badge {
  background: #00ff88;
  color: #0a0e27;
  padding: 0.3rem 0.8rem;
  border-radius: 4px;
  font-weight: bold;
}

.modules-grid {
  display: grid;
  gap: 1rem;
  margin-top: 1rem;
}

.module-card {
  background: #1a1f3a;
  padding: 1rem;
  border-radius: 4px;
}

.module-name {
  color: #00b4d8;
  font-weight: bold;
  text-transform: uppercase;
}

.module-status {
  color: #00ff88;
  font-size: 0.9rem;
  margin: 0.3rem 0;
}

.progress-bar {
  height: 24px;
  background: #0a0e27;
  border-radius: 4px;
  overflow: hidden;
  margin-top: 0.5rem;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #00b4d8, #00ff88);
  display: flex;
  align-items: center;
  justify-content: center;
  color: #0a0e27;
  font-weight: bold;
  transition: width 0.3s ease;
}

.critical-params {
  background: #1a1f3a;
  padding: 1rem;
  border-radius: 4px;
  border-left: 3px solid #ff4444;
}

.param-item {
  display: flex;
  justify-content: space-between;
  padding: 0.5rem 0;
  border-bottom: 1px solid #333;
}

.param-item:last-child {
  border-bottom: none;
}

.param-label {
  color: #888;
}

.param-value {
  color: #00ff88;
  font-weight: bold;
}

.warning-box {
  background: #2a1f1a;
  border: 1px solid #ff8800;
  padding: 1rem;
  border-radius: 4px;
  color: #ffaa00;
  margin-top: 1rem;
  text-align: center;
}

.code-example {
  background: #0a0e27;
  padding: 1rem;
  border-radius: 6px;
  border-left: 3px solid #00ff88;
}

.code-example h4 {
  color: #00b4d8;
  margin-top: 0;
}

.code-example pre {
  color: #00ff88;
  font-size: 0.85rem;
  overflow-x: auto;
  margin: 0;
}

.info-box {
  background: #1a1f3a;
  padding: 1.5rem;
  border-radius: 8px;
  border-left: 4px solid #00ff88;
}

.info-box h3 {
  color: #00ff88;
  margin-top: 0;
}

.use-cases {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 1rem;
  margin-top: 1rem;
}

.use-case {
  background: #0a0e27;
  padding: 1rem;
  border-radius: 4px;
}

.use-case h4 {
  color: #00b4d8;
  margin-top: 0;
}

.use-case p {
  color: #ccc;
  margin: 0;
  font-size: 0.9rem;
}
</style>

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What does the isRef() function return?

  2. 2. What does unref(value) do?

These are 2 of 5 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Code editor

    Create ref and reactive variables and use isRef() and isReactive() to check their types.

  • Click in order

    Arrange the code that checks the type of a value:

  • Code editor

    Write a function that uses unref() to accept both ref and regular values as arguments.

  1. QuestionThe isRef() function
  2. QuestionThe unref() function
  3. Coding taskPractice: isRef and isReactive
  4. QuestionReactivity utility functions
  5. QuestionThe toRaw() function
  6. Click in orderChecking reactivity types
  7. Coding taskPractice: unref() in a function
  8. QuestionReactivity debugging tools

Useful articles