Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 87 ยท Reactivity Fundamentals

Reactive State with ref

Learn how ref() creates reactive state in Vue 3, when you need .value and when you do not, how refs hold objects with deep reactivity, and why refs exist at all.

Reactivity is the heart of Vue. You change a piece of data, and everything on the page that depends on it updates by itself. You have already seen this at work: a ref held the count in a button, a list of fruits grew when you pushed to it. This lesson explains what a ref really is, why you need .value in your script but not in your template, and what "deep" reactivity means.

If JavaScript variables were enough, there would be no need for any of this. But a plain variable such as let count = 0 gives Vue no way to know that it changed. A ref is a small container Vue can watch.

Creating a ref

ref() takes a starting value and returns a ref object with a single property, .value:

JavaScript
import { ref } from "vue";

const count = ref(0);
console.log(count);        // { value: 0 }
console.log(count.value);  // 0

count.value++;
console.log(count.value);  // 1

Reading .value tells Vue "this code depends on count". Writing .value tells Vue "dependents must run again". The container is what makes both visible.

The value can be any type: number, string, boolean, array, object, a Date, even a DOM node.

.value in script, no .value in the template

Inside setup() you always use .value. In the template Vue unwraps top-level refs for you, so you just write the name:

Refs in script and in the template

The template says count, the function says count.value. The inline handler count += 10 works in the template, because the template sees the unwrapped number and assignment through the template writes back into the ref.

Unwrapping has one limit: it applies to top-level properties returned from setup(). A ref nested inside a plain object is not unwrapped when you use it in an interpolation:

JavaScript
const object = { id: ref(1) };

{{ object.id + 1 }} would give [object Object]1, not 2, because object.id is still a ref. Destructure it first (const { id } = object) so it becomes a top-level property, or use {{ object.id.value + 1 }}. A bare {{ object.id }} happens to work, because the text interpolation unwraps a ref at the end.

flowchart LR
  subgraph Script["script: setup()"]
    R["count = ref(0)<br/>{ value: 0 }"]
  end
  subgraph Template["template"]
    T["{{ count }}"]
  end
  R -- "returned from setup, unwrapped" --> T
  T -. "reads .value, so Vue tracks it" .-> R
  R -. "writing .value triggers re-render" .-> T

The template reads count through an automatic .value, and writing .value schedules a re-render.

Why refs exist

JavaScript passes numbers and strings by value. If Vue handed you a plain number, you could copy it into another variable or pass it to a function, and the connection with Vue would vanish; there is nothing to observe when let x = 1; x = 2 runs. Objects are different (Vue can wrap them in a proxy, as the next lesson shows), but primitives cannot be proxied.

A ref solves this by always being an object. You can pass it around, return it from functions, and the .value access is a hook Vue can intercept. The same rule makes refs the building block for composables: a function can return a ref, and the caller keeps a live connection to the data.

A ref keeps its connection when passed around

useTotal receives two refs and returns a computed ref that always matches them. Had we passed price.value (the plain number 5) instead, the total would be stuck at 10. Passing the ref itself passes a live connection. The initial output is Original: 5 | Total: 10.

Refs and objects: deep reactivity

When a ref holds an object or an array, Vue makes the contents deeply reactive. Changing a nested property, pushing to a nested array or replacing the whole object all update the page:

Deep reactivity on a ref of an object

All three buttons update the text. Under the hood, ref converts an object value with reactive() (a proxy), so every level is observed. Deep tracking has a cost for huge structures: if you hold thousands of objects that never change internally, shallowRef() skips the deep conversion (How Reactivity Works).

Because the value is wrapped in a proxy, the object you read back is not identical to the one you put in:

JavaScript
const raw = { n: 1 };
const state = ref(raw);
console.log(state.value === raw); // false, state.value is a proxy of raw
raw.n = 2;                        // changes data, but Vue is not told
state.value.n = 3;                // changes data AND notifies Vue

Always mutate through state.value, never through the original reference.

Replacing versus mutating

Refs make a pattern easy that is awkward elsewhere: swapping the whole value. user.value = newObject is fine and reactive. Likewise items.value = items.value.filter(...) replaces an array. Both are less error-prone than trying to empty an array in place. Assigning a new value, or mutating a property, are equally valid; pick the one that is clearer.

Common ref mistakes

  • Forgetting .value in script. count++ on a ref is a bug: with const it throws a TypeError, and with let it replaces the ref with NaN. You need count.value++.
  • Adding .value in the template. {{ count.value }} is undefined for a top-level ref, because it has already been unwrapped.
  • Destructuring a ref's value into a plain variable and expecting it to stay live: let n = count.value copies the number.
  • Overwriting a ref with a plain value, such as count = 5, when you meant count.value = 5. Declare refs with const to make this a visible error.

These and related traps are collected in Reactivity Pitfalls.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Given const n = ref(1), how do you increase it inside setup()?

    In script you read and write through .value. Only the template unwraps refs automatically.
  2. 2. What do you write in the template to display the ref n?

    Top-level refs returned from setup are unwrapped in the template, so the plain name is enough.
  3. 3. Why is ref a container object instead of just a plain number?

    Assigning to a plain variable gives Vue no signal. Reading and writing .value does.
  4. 4. What happens when you run user.value.address.city = 'Paris' on a ref of a nested object?

    ref wraps object values in a deep reactive proxy, so nested mutations are tracked.

Summary

  • ref(value) returns an object { value } that Vue can track; any type is allowed.
  • Use .value in script; top-level refs are unwrapped automatically in the template.
  • Refs exist because primitives cannot be observed, and because a ref can be passed around while staying connected to its data.
  • A ref holding an object makes it deeply reactive; mutate through .value, never through the original raw object.
  • shallowRef skips the deep conversion when you hold large data that you only ever replace.

Next, see the other way to make an object reactive in reactive Objects.