Vue.js course · Module 3: Reactivity

toRef and toRefs - Safe Sensor Unpacking

5 min read ·
In this lesson6

Sometimes you need to extract individual properties from a reactive sensor object while preserving reactivity - like isolating specific readings from a complex monitoring system.

You want to pass just the temperature to a display function, or give fields shorter names in the template, so you reach for destructuring. It looks innocent, but from a reactive object it takes only a snapshot of a reading at one moment. This lesson shows how to take a property out together with the wire that keeps carrying changes.

The Destructuring Problem

See what happens to values taken out of a reactive() object when the object changes later:

import { reactive } from 'vue'

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

// BAD - loses reactivity!
const { name, temperature } = reactor
console.log(name) // 'Plasma Core Alpha' - but not reactive

reactor.name = 'Plasma Core Beta'
console.log(name) // Still 'Plasma Core Alpha'!

The name variable received a plain string copied at the moment of destructuring. The reactor object changed correctly, but the copy does not know about it and will not refresh any view. The same happens when you pass reactor.temperature to a function: it receives a number, not a connection to the reactor.

toRef() - Single Sensor

toRef(object, 'key') creates a ref linked to a single property. The connection works both ways:

import { reactive, toRef } from 'vue'

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

// toRef creates a reactive reference to a reading
const nameRef = toRef(reactor, 'name')

console.log(nameRef.value) // 'Plasma Core Alpha'

reactor.name = 'Plasma Core Beta'
console.log(nameRef.value) // 'Plasma Core Beta' - synchronized!

nameRef.value = 'Plasma Core Gamma'
console.log(reactor.name) // 'Plasma Core Gamma' - bidirectional!

nameRef does not store its own copy; it reads and writes reactor.name. This is different from ref(reactor.name), which would receive a plain string and be synchronized with nothing.

toRefs() - All Sensors

toRefs() does the same for all properties at once and returns a plain object full of refs that can be destructured safely:

import { reactive, toRefs } from 'vue'

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

// toRefs converts all properties
const { name, temperature, status } = toRefs(reactor)

// Each is now a ref with .value
console.log(name.value) // 'Plasma Core Alpha'
console.log(temperature.value)  // 2500

// Changes are synchronized
reactor.temperature = 2600
console.log(temperature.value) // 2600

toRefs creates refs only for the properties that exist at the moment of the call. A field added later will not get a ref - for an optional field use toRef. The same mechanism helps when a function returns state: returning toRefs(state) lets the caller destructure the result without losing reactivity.

Usage in Components

The station archive keeps holographic copies of Earth's works of art. The edit form uses v-model, the two-way binding directive: typed text goes into the data, and a change of the data goes back into the field. You will learn it in detail in module 5.

<template>
  <div>
    <input v-model="title" />
    <p>Year: {{ year }}</p>
  </div>
</template>

<script setup>
import { reactive, toRefs } from 'vue'

const artwork = reactive({
  title: 'Mona Lisa',
  year: 1503
})

// Unpack for use in template
const { title, year } = toRefs(artwork)
</script>

Typing into the field changes artwork.title through the title ref. In the template you could just as well write artwork.title - toRefs is most useful when you return state from a function or pass it on.

toRef with Default Value

The third argument of toRef is a default value, used when the property is undefined:

import { reactive, toRef } from 'vue'

const reactor = reactive({
  name: 'Plasma Core Alpha'
  // no 'maxTemperature'
})

// With default value (Vue 3.2.25+)
const maxTemperature = toRef(reactor, 'maxTemperature', 5000)
console.log(maxTemperature.value) // 5000

The reactor object did not gain a new field - the default value lives only in the ref. It comes in handy with telemetry batches in which some fields are empty.

Practical Example - Props

Props are data a component receives from its parent. The defineProps macro declares them without an import, and a type written in angle brackets requires lang="ts":

<!-- SensorDisplay.vue -->
<script setup lang="ts">
import { toRefs } from 'vue'

const props = defineProps<{
  sensorName: string
  reading: number
}>()

// Unpack props while preserving reactivity
const { sensorName, reading } = toRefs(props)

// Now you can use them in watch, computed, etc.
</script>

The props object is reactive, so toRefs gives you refs that keep up with the parent. Since Vue 3.5 even variables destructured directly from defineProps() stay reactive, because the compiler turns them into props.sensorName. When you pass such a prop to another function, however, you still need a ref or a getter like () => props.reading. You will get to know components and props in module 6.

My choice: toRef for one field, toRefs for a whole object, and the plain dot notation in a simple template. In the next lesson you will meet tools that tell you whether a value is a ref, a reactive object or just a plain copy.

Remember: destructuring takes a snapshot of a reading, while toRef and toRefs connect a wire that carries changes both ways.

Code for this lesson: App.vue
<script setup>
import { ref, reactive, isRef, isReactive, unref } from 'vue'

// System diagnostics - isRef(), isReactive(), unref()
// Checking reactivity types in NOVA LAB

// Different data types
const systemName = ref('Plasma Core System')
const isPowered = ref(true)
const powerLevel = ref(75)

const systemConfig = reactive({
  id: 'SYS-001',
  type: 'REACTOR',
  online: true,
  sensors: {
    temperature: 850,
    pressure: 120
  }
})

const normalString = 'This is not reactive'
const normalNumber = 42
const normalObject = { test: 'value' }

// Diagnostic function
function diagnoseValue(value, name) {
  return {
    name,
    isRef: isRef(value),
    isReactive: isReactive(value),
    rawValue: unref(value), // unref() returns value without .value
    type: typeof value
  }
}

// Diagnostic results
const diagnosticResults = ref([])

function runDiagnostics() {
  diagnosticResults.value = [
    diagnoseValue(systemName, 'systemName'),
    diagnoseValue(isPowered, 'isPowered'),
    diagnoseValue(powerLevel, 'powerLevel'),
    diagnoseValue(systemConfig, 'systemConfig'),
    diagnoseValue(systemConfig.sensors, 'systemConfig.sensors'),
    diagnoseValue(normalString, 'normalString'),
    diagnoseValue(normalNumber, 'normalNumber'),
    diagnoseValue(normalObject, 'normalObject')
  ]
}

// Example of using unref()
function getValue(maybeRef) {
  // unref() safely extracts value from ref or returns normal value
  return unref(maybeRef)
}

// Universal function accepting ref or value
function updatePowerLevel(newLevel) {
  // Check if it is a ref
  if (isRef(powerLevel)) {
    powerLevel.value = newLevel
  } else {
    console.log('powerLevel is not a ref!')
  }
}

// Universal function for objects
function updateSystemStatus(system, status) {
  if (isReactive(system)) {
    system.online = status
  } else {
    console.log('System is not reactive!')
  }
}

// Practical examples
const mixedData = ref([
  { name: 'Sensor A', value: ref(100) },
  { name: 'Sensor B', value: 200 },
  { name: 'Sensor C', value: ref(300) }
])

function processValue(item) {
  // We use unref() to safely get the value
  const value = unref(item.value)
  return value * 1.1
}

// Run diagnostics on load
runDiagnostics()
</script>

<template>
  <div class="diagnostics">
    <div class="header">
      <h1>SYSTEM DIAGNOSTICS - NOVA LAB</h1>
      <p class="subtitle">isRef(), isReactive(), unref() - Checking reactivity</p>
    </div>

    <div class="system-panel">
      <h2>System Status</h2>
      <div class="status-grid">
        <div class="status-item">
          <div class="label">System Name</div>
          <div class="value">{{ systemName }}</div>
          <div class="type-badge ref">REF</div>
        </div>

        <div class="status-item">
          <div class="label">Power Status</div>
          <div class="value">{{ isPowered ? 'ONLINE' : 'OFFLINE' }}</div>
          <div class="type-badge ref">REF</div>
        </div>

        <div class="status-item">
          <div class="label">Power Level</div>
          <div class="value">{{ powerLevel }}%</div>
          <div class="type-badge ref">REF</div>
        </div>

        <div class="status-item">
          <div class="label">System ID</div>
          <div class="value">{{ systemConfig.id }}</div>
          <div class="type-badge reactive">REACTIVE</div>
        </div>

        <div class="status-item">
          <div class="label">Temperature</div>
          <div class="value">{{ systemConfig.sensors.temperature }}°C</div>
          <div class="type-badge reactive">REACTIVE</div>
        </div>

        <div class="status-item">
          <div class="label">Pressure</div>
          <div class="value">{{ systemConfig.sensors.pressure }} bar</div>
          <div class="type-badge reactive">REACTIVE</div>
        </div>
      </div>
    </div>

    <div class="diagnostics-panel">
      <div class="panel-header">
        <h2>Reactivity Diagnostics Results</h2>
        <button @click="runDiagnostics" class="btn btn-scan">
          Run again
        </button>
      </div>

      <div class="results-table">
        <div class="table-header">
          <div>Variable name</div>
          <div>isRef()</div>
          <div>isReactive()</div>
          <div>Value (unref)</div>
          <div>Type</div>
        </div>
        <div
          v-for="result in diagnosticResults"
          :key="result.name"
          class="table-row"
        >
          <div class="cell-name">{{ result.name }}</div>
          <div class="cell-check">
            <span v-if="result.isRef" class="check-yes">TRUE</span>
            <span v-else class="check-no">FALSE</span>
          </div>
          <div class="cell-check">
            <span v-if="result.isReactive" class="check-yes">TRUE</span>
            <span v-else class="check-no">FALSE</span>
          </div>
          <div class="cell-value">
            {{ typeof result.rawValue === 'object' ? JSON.stringify(result.rawValue) : result.rawValue }}
          </div>
          <div class="cell-type">{{ result.type }}</div>
        </div>
      </div>
    </div>

    <div class="examples-section">
      <h2>Practical examples</h2>

      <div class="example-grid">
        <div class="example-card">
          <h3>unref() - Universal value retrieval</h3>
          <div class="code-box">
            <pre>function getValue(maybeRef) {
  return unref(maybeRef)
}

const refValue = ref(100)
const normalValue = 200

getValue(refValue)    // 100
getValue(normalValue) // 200</pre>
          </div>
          <div class="demo">
            <p>getValue(powerLevel): <strong>{{ getValue(powerLevel) }}</strong></p>
            <p>getValue(normalNumber): <strong>{{ getValue(normalNumber) }}</strong></p>
          </div>
        </div>

        <div class="example-card">
          <h3>isRef() - Checking if a value is a ref</h3>
          <div class="code-box">
            <pre>if (isRef(value)) {
  value.value = newValue
} else {
  // handle normal value
}</pre>
          </div>
          <div class="demo">
            <p>isRef(powerLevel): <strong class="check-yes">{{ isRef(powerLevel) }}</strong></p>
            <p>isRef(normalNumber): <strong class="check-no">{{ isRef(normalNumber) }}</strong></p>
            <button @click="updatePowerLevel(90)" class="btn btn-small">
              Set power to 90%
            </button>
          </div>
        </div>

        <div class="example-card">
          <h3>isReactive() - Checking if an object is reactive</h3>
          <div class="code-box">
            <pre>if (isReactive(obj)) {
  obj.property = newValue
} else {
  // handle normal object
}</pre>
          </div>
          <div class="demo">
            <p>isReactive(systemConfig): <strong class="check-yes">{{ isReactive(systemConfig) }}</strong></p>
            <p>isReactive(normalObject): <strong class="check-no">{{ isReactive(normalObject) }}</strong></p>
            <button @click="updateSystemStatus(systemConfig, !systemConfig.online)" class="btn btn-small">
              Toggle system status
            </button>
          </div>
        </div>

        <div class="example-card">
          <h3>Mixed data - practical case</h3>
          <div class="code-box">
            <pre>// Some values are ref, others are not
const sensors = [
  { name: 'A', value: ref(100) },
  { name: 'B', value: 200 }
]

// unref() handles both cases
sensors.forEach(s => {
  const val = unref(s.value)
})</pre>
          </div>
          <div class="demo">
            <div v-for="item in mixedData" :key="item.name" class="sensor-item">
              <span>{{ item.name }}:</span>
              <span class="sensor-value">{{ processValue(item) }}</span>
              <span v-if="isRef(item.value)" class="type-badge ref">REF</span>
              <span v-else class="type-badge normal">NORMAL</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="info-box">
      <h3>When to use these functions?</h3>
      <ul>
        <li>
          <strong>isRef(value):</strong> Checks if a value is a ref. Useful in universal functions.
        </li>
        <li>
          <strong>isReactive(value):</strong> Checks if an object is reactive. Helps with debugging.
        </li>
        <li>
          <strong>unref(value):</strong> Returns the value from a ref or the original value. Safe way to access.
        </li>
        <li>
          <strong>Practical use:</strong> Creating functions compatible with both ref and normal values.
        </li>
      </ul>
    </div>
  </div>
</template>

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

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

.system-panel h2 {
  color: #00b4d8;
  margin-top: 0;
}

.status-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1rem;
}

.status-item {
  background: #0a0e27;
  padding: 1rem;
  border-radius: 6px;
  position: relative;
}

.label {
  font-size: 0.85rem;
  color: #888;
  margin-bottom: 0.5rem;
}

.value {
  font-size: 1.3rem;
  color: #00ff88;
  font-weight: bold;
}

.type-badge {
  position: absolute;
  top: 0.5rem;
  right: 0.5rem;
  padding: 0.2rem 0.5rem;
  border-radius: 4px;
  font-size: 0.7rem;
  font-weight: bold;
}

.type-badge.ref {
  background: #00b4d8;
  color: #0a0e27;
}

.type-badge.reactive {
  background: #00ff88;
  color: #0a0e27;
}

.type-badge.normal {
  background: #666;
  color: white;
}

.diagnostics-panel {
  background: #1a1f3a;
  padding: 1.5rem;
  border-radius: 8px;
  border: 1px solid #00ff88;
  margin-bottom: 2rem;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
}

.panel-header h2 {
  color: #00ff88;
  margin: 0;
}

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

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

.btn-scan:hover {
  transform: scale(1.05);
  box-shadow: 0 0 20px #00ff88;
}

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

.results-table {
  background: #0a0e27;
  border-radius: 6px;
  overflow: hidden;
}

.table-header, .table-row {
  display: grid;
  grid-template-columns: 2fr 1fr 1fr 2fr 1fr;
  gap: 1rem;
  padding: 1rem;
  align-items: center;
}

.table-header {
  background: #00ff8820;
  color: #00ff88;
  font-weight: bold;
  border-bottom: 2px solid #00ff88;
}

.table-row {
  border-bottom: 1px solid #333;
}

.table-row:hover {
  background: #1a1f3a;
}

.cell-name {
  color: #00b4d8;
  font-family: monospace;
}

.cell-check {
  text-align: center;
}

.check-yes {
  color: #00ff88;
}

.check-no {
  color: #666;
}

.cell-value {
  color: #ccc;
  font-size: 0.9rem;
  overflow: hidden;
  text-overflow: ellipsis;
}

.cell-type {
  color: #888;
  font-style: italic;
}

.examples-section {
  margin-bottom: 2rem;
}

.examples-section h2 {
  color: #00ff88;
  margin-bottom: 1.5rem;
}

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

.example-card {
  background: #1a1f3a;
  padding: 1.5rem;
  border-radius: 8px;
  border: 1px solid #333;
}

.example-card h3 {
  color: #00b4d8;
  margin-top: 0;
  font-size: 1.1rem;
}

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

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

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

.demo p {
  margin: 0.5rem 0;
  color: #ccc;
}

.demo strong {
  color: #00ff88;
}

.sensor-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.5rem;
  margin: 0.3rem 0;
  background: #1a1f3a;
  border-radius: 4px;
}

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

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

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

.info-box ul {
  color: #ccc;
  line-height: 1.8;
}

.info-box strong {
  color: #00b4d8;
}
</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 happens when you destructure a reactive object?

  2. 2. What does toRef() do?

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 reactive object and use toRef() to create a ref linked to a single property.

  • Click in order

    Arrange the elements of toRef() syntax in the correct order.

  • Code editor

    Create a reactive object and use toRefs() for safe destructuring that preserves reactivity.

  • Vertical ordering

    Arrange the steps for safe destructuring with toRefs() in the correct order.

  • Horizontal ordering

    Arrange the elements of destructuring with toRefs in the correct order.

  1. QuestionProblem with destructuring reactive
  2. QuestionThe toRef() function
  3. Coding taskPractice: toRef() single property
  4. Click in ordertoRef syntax
  5. QuestionThe toRefs() function
  6. Coding taskPractice: toRefs() destructuring
  7. Put in orderDestructuring process with toRefs
  8. Put in orderDestructuring with toRefs
  9. QuestiontoRef vs toRefs

Useful articles