Skip to the workspace
Pebellslearn by building
API Styles  ›  Lesson

ref and reactive

Composition API 14 minref wraps any value in a reactive box read through .value, while reactive makes an object itself reactive but breaks when replaced or destructured.

vue / ref and reactive

Explore each scene at your own pace.

01 · The rule

The rule

ref and reactive

Shelf needs filter state: which genre to show and whether to hide finished books. You could store it as two refs or as one reactive object. Both work, until someone destructures the object or replaces it wholesale and the page silently stops updating. Knowing how each tool tracks changes prevents that.

The rule

ref boxes any value in .value; reactive wraps an object, so keep the wrapper.

ref wraps any value, a number, a string, an array or an object, in a small box. You read and write through .value, and Vue notices every write:

import { ref, reactive } from 'vue'

const genre = ref('all')
genre.value = 'science'           // page updates

const books = ref([])
books.value = [{ title: 'Dune' }]  // replacing the whole array is fine
books.value.push({ title: 'Circe' }) // so is changing it in place

reactive takes an object and returns a proxy: a stand-in that notices whenever its properties are read or written. No .value:

const filters = reactive({ genre: 'all', hideFinished: false })
filters.genre = 'science'         // page updates

reactive has three limits, all from the same cause, which is that Vue tracks the proxy itself:

  • Objects only. reactive('all') does not work; strings, numbers and booleans need ref.
  • Do not replace it. filters = reactive({...}) (with let) gives a brand-new proxy; the template still watches the old one.
  • Do not destructure it. const { genre } = filters copies the current string into a plain variable that Vue does not track. If you need separate pieces, toRefs(filters) gives refs linked to each property.

In templates, top-level refs are unwrapped, so {{ genre }} works. Because ref has none of reactive's limits, the Vue docs suggest ref as the default choice.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.