ref and reactive

Beginner · 9 min

Declaring reactive state in Vue 3 with ref() and reactive(), why refs need .value, where Vue unwraps them for you, and how reactivity gets lost.

Before thisscript setup and compiler macrosForm input bindings with v-model

Make Apps with Danny · 9 min

ref and reactive

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Make Apps with DannyReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A plain `let count = 0` in `<script setup>` never updates the page, because Vue has no way to notice a local variable changing. `ref()` and `reactive()` wrap state in objects that report every read and write to Vue.
  • `ref(value)` works for any type and exposes it through `.value`. The wrapper object is what lets Vue intercept access to a primitive like a number, which JavaScript otherwise passes by copy.
  • Templates unwrap top-level refs automatically, so you write `{{ count }}` and `count++` in markup but `count.value` in script. A ref stored as a property of a `reactive()` object is also unwrapped when you read it.
  • `reactive(obj)` returns a deeply reactive Proxy of an object, array, Map, or Set. It cannot hold a primitive, cannot be replaced wholesale without breaking the connection, and loses reactivity when destructured.
  • The Vue docs recommend `ref()` as the default for declaring state. Use `toRefs()` or `toRef()` when you need to pull properties out of a reactive object without cutting them off from the source.

The problem: a variable Vue cannot see

Start with what does not work:

<script setup>
let count = 0

function increment() {
  count++
  console.log(count) // 1, 2, 3... the variable really changes
}
</script>

<template>
  <button @click="increment">Clicked {{ count }} times</button>
</template>

The console shows the number climbing, but the button stays at 0. <script setup> runs once per component instance, and the template’s render function reads count when it first renders. After that, nothing tells Vue the value moved. Assigning to a local variable is just a write to a slot in memory. There is no hook for a framework to sit on.

So Vue needs every piece of state the template depends on to live inside something it can intercept. When the template reads the state, Vue records “this component depends on this value.” When code writes the state, Vue looks up who depended on it and schedules them to update. Both ref() and reactive() exist to put state inside an object where those reads and writes can be caught.

Think of it like a shared spreadsheet cell versus a number you scribbled on a sticky note. Anyone looking at the cell sees edits; nobody gets notified when you change the sticky note.

ref(): a box with a .value

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

const count = ref(0)

function increment() {
  count.value++
}
</script>

<template>
  <button @click="increment">Clicked {{ count }} times</button>
</template>

ref(0) returns a small object whose value property is backed by a getter and a setter. The getter tells Vue “someone read me”; the setter tells Vue “I changed.” That is the whole reason for .value. JavaScript passes numbers, strings, and booleans by copy, so Vue cannot intercept access to a bare 0. It has to give you a box and intercept access to what is inside it.

A ref can hold anything. If you give it an object or array, Vue makes the inner value deeply reactive too, so todos.value.push(item) and user.value.name = 'Ada' both trigger updates. Replacing the whole value with todos.value = [] is tracked as well, which is one of the big practical advantages of refs.

Where Vue unwraps refs for you

Writing .value everywhere would get tiresome, so Vue unwraps refs in a few places:

  • In templates, top-level refs from <script setup> are unwrapped. You write {{ count }} and @click="count++", not count.value.
  • Inside a reactive() object, a ref stored as a property is unwrapped when accessed: reactive({ count: ref(0) }).count gives 0.

The unwrapping does not apply to refs stored inside a reactive array or a Map, and it does not apply in plain script code. The rule of thumb: in <script>, you write .value; in <template>, you don’t. With TypeScript, a forgotten .value usually surfaces as a type error, since a Ref<number> is not a number.

reactive(): a Proxy around an object

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

const form = reactive({
  email: '',
  agreed: false,
})
</script>

<template>
  <input v-model="form.email" type="email" />
  <input v-model="form.agreed" type="checkbox" />
  <p v-if="form.agreed">Sending to {{ form.email }}</p>
</template>

reactive() wraps an object in a JavaScript Proxy, so every property read and write on form passes through Vue first. No .value is needed, because the object itself is already the box. It is deep: form.address.city = 'Oslo' is tracked too, and nested objects come back as proxies when you read them.

That convenience comes with three hard limits:

  1. Objects only. reactive(0) does nothing useful. Primitives need ref().
  2. You cannot replace it. If you write form = reactive({ ... }), the template still holds the old proxy and will never see the new one. Mutate properties instead, or use Object.assign(form, newValues).
  3. Destructuring disconnects. const { email } = form copies the current string into a plain variable. Passing form.email into a function does the same. Either way, the copy has no link back to the proxy.

One more subtlety: the proxy is not the original object. reactive(raw) === raw is false. Calling reactive(raw) again returns the same proxy, but mutating raw directly bypasses Vue entirely. Keep working with the proxy.

Keeping the connection: toRefs and toRef

When you genuinely need to pull properties out of a reactive object, convert them to refs first:

import { reactive, toRefs, toRef } from 'vue'

const form = reactive({ email: '', agreed: false })

const { email, agreed } = toRefs(form) // each is a ref linked to form
email.value = 'ada@example.com'        // form.email is now updated too

const onlyEmail = toRef(form, 'email') // one property

These refs do not copy anything. Reading email.value reads form.email, and writing it writes form.email. This is the standard way to destructure reactive state while keeping it live. It shows up constantly once you start returning state from composables.

Which one to use

The official Vue docs recommend ref() as the primary way to declare reactive state, and the reasons fall straight out of the limits above. A ref works for every type, survives being replaced, and survives being passed around, since you pass the box, not its contents. reactive() is fine for a cluster of fields that always travel together, like a form model, as long as you never reassign it and never destructure it without toRefs().

If you come from React, notice what is missing: there is no setter function and no re-render of the whole component. count.value++ is an ordinary mutation, and Vue figures out exactly which parts of the page read count. The how Vue reactivity works lesson takes that mechanism apart; React’s contrasting model is in useState and component state.

What the video covers

Danny’s episode builds a small counter and form with the Composition API and walks through exactly the beginner sequence this lesson needs: declaring refs, binding them two ways with v-model, grouping related data into a reactive() object, and leaving data that never changes as plain, non-reactive values. It is from 2022, but ref() and reactive() have not changed since. It does not spend time on how reactivity gets lost when you destructure, which is why that half is carried above in prose.

For the gotchas, Alexander Lichter’s video in the “go deeper” links is the best follow-up. It walks through each way the reactive connection breaks, with refs, props, and reactive(). Program With Erik’s video covers more utilities (isRef, unref, toRefs, customRef), but its final chapter presents “Ref Sugar,” the Reactivity Transform, as future syntax. That proposal was abandoned and removed from Vue core in 3.4. Skip that part.

Where this fits

Once state is reactive, the next step is deriving values from it without recomputing them by hand. That is computed properties.

Check yourself

  1. 01Why does `let count = 0; function inc() { count++ }` in `<script setup>` never update the template, even though `count` really does change?

    Vue only re-renders when it is told that something the template read has changed. Reading and assigning a plain local variable is invisible to Vue: there is no object it can intercept, so nothing records that the template depends on `count` and nothing fires when it changes. Wrapping it as `const count = ref(0)` and incrementing `count.value` routes both the read and the write through an object Vue controls.

  2. 02Given `const state = reactive({ count: 0 })`, why does `let { count } = state` followed by `count++` leave the template unchanged?

    Destructuring copies the current value of `state.count`, the number 0, into a new local variable. That variable has no link back to the Proxy, so incrementing it changes only the copy. Either keep writing `state.count++`, or use `const { count } = toRefs(state)` to get a ref that reads and writes through to `state.count`.

  3. 03Why is `state = reactive({ items: [] })` inside a function a bug when `state` was declared with `let state = reactive({ items: [] })` and used in the template?

    The template captured a reference to the original Proxy. Assigning a new `reactive()` object to the variable makes the variable point somewhere else, but the template is still reading the old Proxy, which never changes again. With `reactive()` you mutate properties (`state.items = newItems`); if you need to swap the whole value, hold it in a `ref` and assign `.value`, which Vue does track.

  4. 04When would you still reach for `reactive()` over `ref()`?

    When you have a group of related fields that always travel together as one object, such as a form model, and you like writing `form.email` without `.value`. It is a stylistic choice with trade-offs: you must never replace the object or destructure it without `toRefs()`. For single values, values that get replaced, or anything returned from a composable, `ref()` avoids those traps.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark