We use cookies to enhance your experience on the site
CodeWorlds

Deep vs Shallow Reactivity

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

Deep Reactivity (default)

1import { ref, reactive } from 'vue'
2
3// ref with object - deep reactivity
4const missionControl = ref({
5  station: 'NOVA LAB',
6  modules: [
7    { id: 1, name: 'Oxygen Generator' },
8    { id: 2, name: 'Water Recycler' }
9  ]
10})
11
12// Changes at any level are reactive
13missionControl.value.station = 'NOVA LAB Alpha'
14missionControl.value.modules[0].name = 'Oxygen Generator Prime'
15missionControl.value.modules.push({ id: 3, name: 'Power Core' })
16// All of the above will trigger a control panel update

shallowRef() - Shallow Reactivity

1import { shallowRef } from 'vue'
2
3const missionControl = shallowRef({
4  station: 'NOVA LAB',
5  modules: [{ id: 1, name: 'Oxygen Generator' }]
6})
7
8// Only .value replacement is reactive
9missionControl.value.station = 'New name' // Will NOT trigger update!
10missionControl.value.modules.push({...}) // Will NOT trigger update!
11
12// THIS will work - replacing the entire object
13missionControl.value = {
14  station: 'NOVA LAB Beta',
15  modules: []
16}

shallowReactive()

1import { shallowReactive } from 'vue'
2
3const missionControl = shallowReactive({
4  station: 'NOVA LAB',
5  location: {
6    planet: 'Mars',
7    year: 2087
8  }
9})
10
11missionControl.station = 'New station' // Reactive - level 1
12missionControl.location.planet = 'Europa' // NOT reactive - level 2
13
14// You must replace the entire location object
15missionControl.location = { planet: 'Europa', year: 2087 }

When to use shallow?

| Situation | Use | |----------|------| | Large objects from API | shallowRef | | External libraries | shallowRef | | Performance optimization | shallow* | | Typical UI data | ref/reactive |

Practical Example

1<template>
2  <div class="sensor-display" style="background: #0a0e27; color: #00ff88;">
3    <h2>{{ sensorData.systemName }}</h2>
4    <button @click="refreshData">Refresh readings</button>
5  </div>
6</template>
7
8<script setup>
9import { shallowRef } from 'vue'
10
11// Large sensor data - shallow reactivity
12const sensorData = shallowRef({
13  systemName: 'Reactor Monitoring',
14  readings: [] // Thousands of sensor readings
15})
16
17async function refreshData() {
18  const response = await fetch('/api/sensors')
19  // Replacing the entire object - reactive
20  sensorData.value = await response.json()
21}
22</script>
Go to CodeWorlds