Vue.js course · Module 3: Reactivity

Reactivity in Vue - The Living Plasma Reactor

5 min read ·
In this lesson5

Welcome to the NOVA LAB Plasma Reactor! Dr. Nova says: here sensors come alive - just as data in Vue becomes reactive and automatically updates the control interface. Every power, temperature, or pressure reading is instantly visible on the panels.

In module 2 you wrote templates that refreshed themselves after data changes, and you took that on faith. In this module we look inside that mechanism, because without understanding it you will sooner or later run into a panel that stubbornly shows an old reading.

What you will learn

  • explain what reactivity is and how Vue tracks data changes,
  • create reactive values with ref() and use .value deliberately,
  • build reactive objects with reactive() and work around its limitations,
  • choose deep or shallow reactivity: shallowRef, shallowReactive, triggerRef,
  • unpack objects safely with toRef and toRefs,
  • diagnose state with isRef, isReactive, unref, toRaw and markRaw,
  • protect state with readonly() and arrange it into a clear architecture.

What is Reactivity?

Let us start with the problem. In plain JavaScript, changing a variable leaves no trace, so the screen has no way to find out about it:

let powerLevel = 0
document.querySelector('#power').textContent = powerLevel

powerLevel = 75
// the screen still shows 0 - nobody knows about the change

To refresh the panel, you would have to find the element and write the new value by hand after every change. Reactivity is a system that automatically tracks data changes and updates the DOM. When you change a value - like the reactor's power level - Vue "knows" and refreshes the view on the control panel.

<template>
  <div class="reactor-panel" style="background: #0a0e27; color: #00ff88;">
    <p>Status: {{ reactorStatus }}</p>
    <button @click="changeStatus">Change status</button>
  </div>
</template>

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

const reactorStatus = ref('STANDBY')

function changeStatus() {
  reactorStatus.value = 'ACTIVE'
  // Vue will automatically update the control panel!
}
</script>

While rendering, the template reads reactorStatus, and Vue notes: this component depends on that sensor. When changeStatus assigns a new value, Vue re-renders the dependent component. DOM updates are batched and applied on the next tick (nextTick), so ten changes in a row result in a single refresh.

ref() - Reactive Sensor

ref() creates a reactive "wrapper" for a value - like a reactor sensor monitoring parameters. It takes an initial value of any type and returns a container with a .value property:

import { ref } from 'vue'

// For primitives - single readings
const powerLevel = ref(0)
const statusMessage = ref('System initializing...')
const isOnline = ref(true)

// For objects (also works) - complex sensor data
const reactor = ref({
  name: 'Plasma Core Alpha',
  temperature: 2500
})

// Accessing the value - use .value
console.log(powerLevel.value) // 0
powerLevel.value++
console.log(powerLevel.value) // 1

// In template - no .value needed!
// {{ powerLevel }} - Vue does this automatically

In the script you always write .value. Refs declared at the top level of <script setup> are unwrapped by the template automatically, so .value is unnecessary there. The variable stays const: the content of the container changes, not the container itself. In module 2 such a container also held a DOM element - it is still the same function, and the ref attribute was what put the element into it.

Why .value?

JavaScript cannot intercept reading or writing a plain variable, but it can intercept access to an object's property. ref() wraps the value in an object with a .value property - like a sensor packing raw data for transmission:

const powerLevel = ref(0)

// Under the hood:
// powerLevel = { value: 0 }

// Changing the value
powerLevel.value = 75 // the .value setter detects the change → panel update

The { value: 0 } notation is a simplification. In reality .value has a getter that records who reads the value, and a setter that notifies those readers about a change. Objects created with reactive() in the next lesson work differently: there Vue uses the Proxy mechanism.

Typing ref (TypeScript)

In a component with <script setup lang="ts">, TypeScript usually infers the ref type on its own. You import the Ref<T> type with import type when you want to write it explicitly, and the Sensor interface describes the shape of the sensor data:

import { ref } from 'vue'
import type { Ref } from 'vue'

// Automatic type inference
const temperature = ref(0) // Ref<number>
const sensorName = ref('Temperature Alpha') // Ref<string>

// Explicit typing
const missionYear: Ref<number> = ref(2087)

// For complex types
interface Sensor {
  name: string
  unit: string
  maxValue: number
}

const temperatureSensor = ref<Sensor>({
  name: 'Plasma Core Temperature',
  unit: 'Kelvin',
  maxValue: 5000
})

The ref<Sensor>() form passes the type in angle brackets. If you specify the type but omit the initial value, the type will also include undefined.

The Vue docs recommend ref() as the primary tool for declaring state, and that is how I work too. In the next lesson you will see reactive(), which covers a whole panel at once but comes with its own limitations.

Remember: ref() is a sensor in a capsule - in the script you open the capsule with .value, and the template hologram does it for you.

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

// Plasma Reactor - Basic reactivity
// ref() for primitive values (numbers, strings, booleans)
const reactorPower = ref(0)
const isOnline = ref(false)
const reactorStatus = ref('OFFLINE')

// reactive() for objects
const plasmaCore = reactive({
  temperature: 0,
  pressure: 0,
  stability: 100,
  fuelLevel: 100
})

function startReactor() {
  isOnline.value = true
  reactorStatus.value = 'INITIALIZING'

  // Reactor startup simulation
  const interval = setInterval(() => {
    if (reactorPower.value < 100) {
      reactorPower.value += 10
      plasmaCore.temperature += 150
      plasmaCore.pressure += 5
      plasmaCore.fuelLevel -= 2
    } else {
      reactorStatus.value = 'ONLINE'
      clearInterval(interval)
    }
  }, 300)
}

function shutdownReactor() {
  isOnline.value = false
  reactorStatus.value = 'OFFLINE'
  reactorPower.value = 0
  plasmaCore.temperature = 0
  plasmaCore.pressure = 0
  plasmaCore.stability = 100
  plasmaCore.fuelLevel = 100
}
</script>

<template>
  <div class="reactor-control">
    <div class="header">
      <h1>PLASMA REACTOR - NOVA LAB</h1>
      <p class="subtitle">Vue.js Reactivity System - ref() and reactive()</p>
    </div>

    <div class="status-grid">
      <div class="status-card">
        <div class="label">REACTOR STATUS</div>
        <div :class="['value', isOnline ? 'online' : 'offline']">
          {{ reactorStatus }}
        </div>
      </div>

      <div class="status-card">
        <div class="label">OUTPUT POWER</div>
        <div class="value accent">{{ reactorPower }}%</div>
        <div class="progress-bar">
          <div class="progress-fill" :style="{ width: reactorPower + '%' }"></div>
        </div>
      </div>
    </div>

    <div class="plasma-grid">
      <div class="plasma-card">
        <div class="icon">◆</div>
        <div class="label">TEMPERATURE</div>
        <div class="value">{{ plasmaCore.temperature.toFixed(0) }}°C</div>
      </div>

      <div class="plasma-card">
        <div class="icon">◆</div>
        <div class="label">PRESSURE</div>
        <div class="value">{{ plasmaCore.pressure }} bar</div>
      </div>

      <div class="plasma-card">
        <div class="icon">◆</div>
        <div class="label">STABILITY</div>
        <div class="value">{{ plasmaCore.stability }}%</div>
      </div>

      <div class="plasma-card">
        <div class="icon">◆</div>
        <div class="label">FUEL</div>
        <div class="value">{{ plasmaCore.fuelLevel }}%</div>
      </div>
    </div>

    <div class="controls">
      <button
        @click="startReactor"
        :disabled="isOnline"
        class="btn btn-start"
      >
        START REACTOR
      </button>
      <button
        @click="shutdownReactor"
        :disabled="!isOnline"
        class="btn btn-stop"
      >
        SHUT DOWN REACTOR
      </button>
    </div>

    <div class="info-box">
      <h3>Learning Reactivity</h3>
      <p><strong>ref():</strong> Used for primitive values (reactorPower, isOnline)</p>
      <p><strong>reactive():</strong> Used for objects (plasmaCore)</p>
      <p><strong>Access:</strong> ref requires .value, reactive does not</p>
    </div>
  </div>
</template>

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

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

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

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

.value {
  font-size: 1.8rem;
  font-weight: bold;
  color: #fff;
}

.value.online {
  color: #00ff88;
  text-shadow: 0 0 10px #00ff88;
}

.value.offline {
  color: #ff4444;
}

.value.accent {
  color: #00b4d8;
}

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

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #00b4d8, #00ff88);
  transition: width 0.3s ease;
}

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

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

.plasma-card .icon {
  font-size: 2rem;
  margin-bottom: 0.5rem;
}

.plasma-card .value {
  font-size: 1.5rem;
  color: #00ff88;
}

.controls {
  display: flex;
  gap: 1rem;
  margin-bottom: 2rem;
  justify-content: center;
}

.btn {
  padding: 1rem 2rem;
  font-size: 1.1rem;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-weight: bold;
  transition: all 0.3s ease;
  font-family: 'Courier New', monospace;
}

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

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

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

.btn-stop:hover:not(:disabled) {
  transform: scale(1.05);
  box-shadow: 0 0 20px #ff4444;
}

.btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.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 p {
  margin: 0.5rem 0;
  color: #ccc;
}

.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 is reactivity in Vue.js?

  2. 2. What is ref() used for in Vue 3?

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

Hands-on tasks in the game

  • Code editor

    Create reactive variables using ref() for the station name and temperature, and display them in the template.

  • Click in order

    Arrange the steps for creating and using ref() in the correct order.

  • Code editor

    Create a counter with increment and decrement buttons using ref().

  • Vertical ordering

    Arrange the steps for creating reactive state with ref() in the correct order.

  1. QuestionWhat is reactivity?
  2. QuestionThe ref() function
  3. Coding taskPractice: ref() basics
  4. QuestionAccessing the ref value
  5. Click in orderCreating ref step by step
  6. Coding taskPractice: Counter with ref()
  7. QuestionRef in template
  8. Put in orderProcess of creating reactive state

Useful articles