Vue.js course ยท Module 3: Reactivity

Deep vs Shallow Reactivity

5 min read ยท
In this lesson5

Vue offers different levels of reactivity - like different layers of sensors in a reactor.

Every few seconds the reactor telemetry sends a batch of thousands of readings. You replace the whole batch every time, and yet default reactivity wraps every nested object you touch in a Proxy and tracks every reading separately. It is like mounting a sensor on every bolt of the cargo when all you care about is whether a new crate has arrived. For such situations Vue has shallow versions.

Deep Reactivity (default)

By default reactivity is deep: ref() holding an object and reactive() track changes at every level of nesting, arrays included.

import { ref, reactive } from 'vue'

// ref with object - deep reactivity
const missionControl = ref({
  station: 'NOVA LAB',
  modules: [
    { id: 1, name: 'Oxygen Generator' },
    { id: 2, name: 'Water Recycler' }
  ]
})

// Changes at any level are reactive
missionControl.value.station = 'NOVA LAB Alpha'
missionControl.value.modules[0].name = 'Oxygen Generator Prime'
missionControl.value.modules.push({ id: 3, name: 'Power Core' })
// All of the above will trigger a control panel update

Each of the three changes refreshes the panel, because ref() passed the object to reactive(), which wraps nested objects as soon as you reach for them. For typical interface data this is convenient and fast enough.

shallowRef() - Shallow Reactivity

shallowRef() stores the value without turning it into a Proxy. Only access to .value is reactive, which means replacing the whole content:

import { shallowRef } from 'vue'

const missionControl = shallowRef({
  station: 'NOVA LAB',
  modules: [{ id: 1, name: 'Oxygen Generator' }]
})

// Only .value replacement is reactive
missionControl.value.station = 'New name' // Will NOT trigger update!
missionControl.value.modules.push({ id: 2, name: 'Water Recycler' }) // Will NOT trigger update!

// THIS will work - replacing the entire object
missionControl.value = {
  station: 'NOVA LAB Beta',
  modules: []
}

The first two changes really are saved in memory - only the screen does not change, because Vue does not know about them. They will show up at the next render triggered by something else. To change one field in a shallowRef called sensorData, build a new object with the spread operator:

sensorData.value = {
  ...sensorData.value,
  temperature: 3000
}

The new object goes through the .value setter, so the view refreshes, and the old data batch stays untouched. Copying a huge array just to add one element can be wasteful, though. In that case you change the content in place and call triggerRef(), which manually runs everything that depends on the shallow ref:

import { shallowRef, triggerRef } from 'vue'

const readings = shallowRef([])

readings.value.push({ id: 1, temperature: 2500 }) // the view does not know yet
triggerRef(readings) // force an update

After triggerRef the view refreshes once. The responsibility for that call is yours - forget it, and the panel will show old data.

shallowReactive()

shallowReactive() makes only the first-level properties reactive. Nested objects are stored as they are, so Vue cannot see inside them:

import { shallowReactive } from 'vue'

const missionControl = shallowReactive({
  station: 'NOVA LAB',
  location: {
    planet: 'Mars',
    year: 2087
  }
})

missionControl.station = 'New station' // Reactive - level 1
missionControl.location.planet = 'Europa' // NOT reactive - level 2

// You must replace the entire location object
missionControl.location = { planet: 'Europa', year: 2087 }

Replacing location is a change to a first-level property, which is why it works. The docs warn: use shallow structures only as the root state of a component, and do not nest them inside deeply reactive objects, because that creates a tree with inconsistent behavior.

When to use shallow?

Shallow versions are an optimization tool, not a new default choice:

SituationUse
Large objects from APIshallowRef
External librariesshallowRef
Performance optimizationshallow*
Typical UI dataref/reactive

My advice: start with ref and reactive, and reach for the shallow versions for large, immutable data or state managed by an external library.

Practical Example

The monitoring panel fetches sensor data and always replaces the whole batch. The template shows the system name and a refresh button:

<template>
  <div class="sensor-display" style="background: #0a0e27; color: #00ff88;">
    <h2>{{ sensorData.systemName }}</h2>
    <button @click="refreshData">Refresh readings</button>
  </div>
</template>

The script keeps the data in a shallowRef, and an asynchronous function fetches new data with fetch, the browser API for network requests:

<script setup>
import { shallowRef } from 'vue'

// Large sensor data - shallow reactivity
const sensorData = shallowRef({
  systemName: 'Reactor Monitoring',
  readings: [] // Thousands of sensor readings
})

async function refreshData() {
  const response = await fetch('/api/sensors')
  // Replacing the entire object - reactive
  sensorData.value = await response.json()
}
</script>

await waits for the response, and then the assignment to .value refreshes the panel. Vue does not wrap thousands of readings, because nobody modifies them one by one. In the next lesson you will pull single properties out of a reactive object without breaking the connection.

Remember: deep reactivity is a sensor on every bolt, and shallow reactivity is one sensor on the hatch - it notices only a swap of the whole cargo or a manual triggerRef signal.

Code for this lesson: App.vue
<script setup>
import { reactive, toRef, toRefs } from 'vue'

// toRef() and toRefs() - Extracting reactive properties
// NOVA LAB crew member management system

const crewMember = reactive({
  id: 'CREW-001',
  name: 'Dr. Sarah Chen',
  role: 'Chief Engineer',
  status: 'ACTIVE',
  stats: {
    health: 95,
    energy: 80,
    morale: 90
  },
  certifications: ['Reactor Operations', 'EVA Specialist', 'Life Support'],
  missions: 12
})

// toRef() - creates a ref to a single property
// Remains reactive and synchronized with the original object
const memberName = toRef(crewMember, 'name')
const memberStatus = toRef(crewMember, 'status')
const memberHealth = toRef(crewMember.stats, 'health')

// toRefs() - creates refs to all properties of an object
// Useful for destructuring
const { role, missions } = toRefs(crewMember)

// Second crew member for demonstration
const secondCrew = reactive({
  id: 'CREW-002',
  name: 'Cpt. Marcus Rodriguez',
  role: 'Mission Commander',
  status: 'ACTIVE',
  stats: {
    health: 88,
    energy: 75,
    morale: 85
  },
  certifications: ['Command', 'Navigation', 'Emergency Response'],
  missions: 25
})

// We use toRefs() for destructuring
const {
  name: secondName,
  role: secondRole,
  missions: secondMissions,
  status: secondStatus
} = toRefs(secondCrew)

// Modification functions
function updateStatus(newStatus) {
  // Modification via toRef - changes the original object
  memberStatus.value = newStatus
}

function decreaseHealth() {
  // Modification via toRef - affects the original object
  if (memberHealth.value > 0) {
    memberHealth.value -= 10
  }
}

function increaseMissions() {
  // Modification via toRefs - affects the original object
  missions.value++
}

function changeRole(newRole) {
  // Modification via toRefs - affects the original object
  role.value = newRole
}

function promoteSecondCrew() {
  secondMissions.value++
  if (secondMissions.value > 30) {
    secondRole.value = 'Senior Commander'
    secondStatus.value = 'VETERAN'
  }
}
</script>

<template>
  <div class="crew-management">
    <div class="header">
      <h1>CREW MANAGEMENT - NOVA LAB</h1>
      <p class="subtitle">toRef() and toRefs() - Extracting reactive properties</p>
    </div>

    <div class="crew-grid">
      <!-- First crew member - toRef() -->
      <div class="crew-card">
        <div class="crew-header">
          <h2>{{ crewMember.name }}</h2>
          <span :class="'status-badge status-' + crewMember.status.toLowerCase()">
            {{ crewMember.status }}
          </span>
        </div>

        <div class="crew-info">
          <p><strong>ID:</strong> {{ crewMember.id }}</p>
          <p><strong>Role:</strong> {{ crewMember.role }}</p>
          <p><strong>Missions:</strong> {{ crewMember.missions }}</p>
        </div>

        <div class="stats-section">
          <h3>Statistics</h3>
          <div class="stat-bar">
            <label>Health</label>
            <div class="progress">
              <div class="progress-fill health" :style="{ width: crewMember.stats.health + '%' }">
                {{ crewMember.stats.health }}%
              </div>
            </div>
          </div>
          <div class="stat-bar">
            <label>Energy</label>
            <div class="progress">
              <div class="progress-fill energy" :style="{ width: crewMember.stats.energy + '%' }">
                {{ crewMember.stats.energy }}%
              </div>
            </div>
          </div>
          <div class="stat-bar">
            <label>Morale</label>
            <div class="progress">
              <div class="progress-fill morale" :style="{ width: crewMember.stats.morale + '%' }">
                {{ crewMember.stats.morale }}%
              </div>
            </div>
          </div>
        </div>

        <div class="certifications">
          <h3>Certifications</h3>
          <div class="cert-tags">
            <span v-for="cert in crewMember.certifications" :key="cert" class="cert-tag">
              {{ cert }}
            </span>
          </div>
        </div>

        <div class="controls">
          <button @click="updateStatus('ON_MISSION')" class="btn btn-small">
            Send on mission
          </button>
          <button @click="updateStatus('RESTING')" class="btn btn-small">
            Rest
          </button>
          <button @click="decreaseHealth()" class="btn btn-small btn-warning">
            Simulate injury
          </button>
          <button @click="increaseMissions()" class="btn btn-small btn-success">
            Add mission
          </button>
        </div>

        <div class="code-box">
          <pre>// toRef() - single property
const name = toRef(crewMember, 'name')
const health = toRef(crewMember.stats, 'health')

// Modification
health.value -= 10</pre>
        </div>
      </div>

      <!-- Second crew member - toRefs() -->
      <div class="crew-card">
        <div class="crew-header">
          <h2>{{ secondCrew.name }}</h2>
          <span :class="'status-badge status-' + secondCrew.status.toLowerCase()">
            {{ secondCrew.status }}
          </span>
        </div>

        <div class="crew-info">
          <p><strong>ID:</strong> {{ secondCrew.id }}</p>
          <p><strong>Role:</strong> {{ secondRole }}</p>
          <p><strong>Missions:</strong> {{ secondMissions }}</p>
        </div>

        <div class="stats-section">
          <h3>Statistics</h3>
          <div class="stat-bar">
            <label>Health</label>
            <div class="progress">
              <div class="progress-fill health" :style="{ width: secondCrew.stats.health + '%' }">
                {{ secondCrew.stats.health }}%
              </div>
            </div>
          </div>
          <div class="stat-bar">
            <label>Energy</label>
            <div class="progress">
              <div class="progress-fill energy" :style="{ width: secondCrew.stats.energy + '%' }">
                {{ secondCrew.stats.energy }}%
              </div>
            </div>
          </div>
          <div class="stat-bar">
            <label>Morale</label>
            <div class="progress">
              <div class="progress-fill morale" :style="{ width: secondCrew.stats.morale + '%' }">
                {{ secondCrew.stats.morale }}%
              </div>
            </div>
          </div>
        </div>

        <div class="certifications">
          <h3>Certifications</h3>
          <div class="cert-tags">
            <span v-for="cert in secondCrew.certifications" :key="cert" class="cert-tag">
              {{ cert }}
            </span>
          </div>
        </div>

        <div class="controls">
          <button @click="promoteSecondCrew()" class="btn btn-small btn-success">
            Promote
          </button>
          <button @click="changeRole('Flight Director')" class="btn btn-small">
            Change role
          </button>
          <button @click="secondStatus.value = 'ACTIVE'" class="btn btn-small">
            Activate
          </button>
        </div>

        <div class="code-box">
          <pre>// toRefs() - all properties
const { role, missions, status } = toRefs(secondCrew)

// Modification
missions.value++
role.value = 'Senior Commander'</pre>
        </div>
      </div>
    </div>

    <div class="info-box">
      <h3>Difference between toRef() and toRefs()</h3>
      <div class="comparison-grid">
        <div class="comparison-item">
          <h4>toRef(object, 'key')</h4>
          <ul>
            <li>Creates a ref to a <strong>single</strong> property</li>
            <li>Useful when we only need one value</li>
            <li>Maintains reactivity with the original object</li>
            <li>Example: <code>const name = toRef(user, 'name')</code></li>
          </ul>
        </div>
        <div class="comparison-item">
          <h4>toRefs(object)</h4>
          <ul>
            <li>Creates refs to <strong>all</strong> properties</li>
            <li>Useful for destructuring</li>
            <li>Each property becomes a ref</li>
            <li>Example: <code>const { name, age } = toRefs(user)</code></li>
          </ul>
        </div>
      </div>
      <div class="warning-box">
        <p><strong>Important:</strong> Regular destructuring will lose reactivity!</p>
        <code>const { name } = crewMember // Not reactive</code><br>
        <code>const { name } = toRefs(crewMember) // Reactive</code>
      </div>
    </div>
  </div>
</template>

<style scoped>
.crew-management {
  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;
}

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

.crew-card {
  background: #1a1f3a;
  padding: 1.5rem;
  border-radius: 8px;
  border: 1px solid #00b4d8;
}

.crew-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
  padding-bottom: 1rem;
  border-bottom: 1px solid #333;
}

.crew-header h2 {
  color: #00ff88;
  margin: 0;
  font-size: 1.3rem;
}

.status-badge {
  padding: 0.3rem 0.8rem;
  border-radius: 20px;
  font-size: 0.8rem;
  font-weight: bold;
}

.status-active {
  background: #00ff88;
  color: #0a0e27;
}

.status-on_mission {
  background: #00b4d8;
  color: #0a0e27;
}

.status-resting {
  background: #ffaa00;
  color: #0a0e27;
}

.status-veteran {
  background: linear-gradient(135deg, #ffd700, #ffaa00);
  color: #0a0e27;
}

.crew-info p {
  margin: 0.5rem 0;
  color: #ccc;
}

.stats-section {
  margin: 1.5rem 0;
}

.stats-section h3 {
  color: #00b4d8;
  font-size: 1rem;
  margin-bottom: 1rem;
}

.stat-bar {
  margin-bottom: 1rem;
}

.stat-bar label {
  display: block;
  font-size: 0.9rem;
  color: #888;
  margin-bottom: 0.3rem;
}

.progress {
  height: 24px;
  background: #0a0e27;
  border-radius: 4px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #0a0e27;
  font-weight: bold;
  font-size: 0.85rem;
  transition: width 0.3s ease;
}

.progress-fill.health {
  background: linear-gradient(90deg, #ff4444, #ff6666);
}

.progress-fill.energy {
  background: linear-gradient(90deg, #00b4d8, #00d4ff);
}

.progress-fill.morale {
  background: linear-gradient(90deg, #00ff88, #44ffaa);
}

.certifications {
  margin: 1.5rem 0;
}

.certifications h3 {
  color: #00b4d8;
  font-size: 1rem;
  margin-bottom: 0.8rem;
}

.cert-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
}

.cert-tag {
  background: #0a0e27;
  padding: 0.4rem 0.8rem;
  border-radius: 4px;
  border: 1px solid #00ff88;
  color: #00ff88;
  font-size: 0.85rem;
}

.controls {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
  margin: 1rem 0;
}

.btn {
  padding: 0.6rem 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;
  background: #00b4d8;
  color: #0a0e27;
}

.btn-small {
  font-size: 0.85rem;
  padding: 0.5rem 0.8rem;
}

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

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

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

.code-box {
  background: #0a0e27;
  padding: 1rem;
  border-radius: 4px;
  border-left: 3px solid #00ff88;
  margin-top: 1rem;
}

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

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

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

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

.comparison-item h4 {
  color: #00b4d8;
  margin-top: 0;
}

.comparison-item ul {
  padding-left: 1.5rem;
  color: #ccc;
}

.comparison-item li {
  margin: 0.5rem 0;
}

.comparison-item code {
  background: #0a0e27;
  padding: 0.2rem 0.5rem;
  border-radius: 3px;
  color: #00ff88;
}

.warning-box {
  background: #2a1f1a;
  padding: 1rem;
  border-radius: 4px;
  border-left: 3px solid #ffaa00;
  margin-top: 1rem;
}

.warning-box code {
  background: #0a0e27;
  padding: 0.3rem 0.6rem;
  border-radius: 3px;
  color: #00ff88;
  display: inline-block;
  margin: 0.2rem 0;
}
</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. How deep is the default reactivity of ref() and reactive()?

  2. 2. How does shallowRef() differ from ref()?

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

Hands-on tasks in the game

  • Code editor

    Create a shallowRef with an object and demonstrate the difference - modifying a nested property won't trigger a re-render.

  • Horizontal ordering

    Arrange the elements for correctly updating a shallowRef in the correct order.

  • Click in order

    Arrange the reactive functions from deepest to shallowest reactivity.

  • Code editor

    Create a shallowReactive object and show the difference between modifying first-level and nested properties.

  1. QuestionDefault reactivity depth
  2. QuestionshallowRef() vs ref()
  3. Coding taskPractice: shallowRef()
  4. Put in orderUpdating shallowRef
  5. QuestionshallowReactive()
  6. Click in orderReactivity hierarchy
  7. Coding taskPractice: shallowReactive()
  8. QuestionWhen to use shallowRef

Useful articles