Shallow reactivity and escape hatches

Advanced · 12 min

When deep reactivity costs more than it gives, and how shallowRef, shallowReactive, triggerRef, markRaw, toRaw, readonly, and customRef opt you out.

Before thisHow Vue reactivity works

Alexander Lichter · 12 min

Shallow reactivity and escape hatches

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

Taught by Alexander LichterReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Deep reactivity is not free: every nested object Vue touches becomes a Proxy and every read is tracked. For large data you replace wholesale, or for objects owned by another library, that work buys nothing.
  • `shallowRef()` only tracks `.value` itself. Replacing the value triggers updates; mutating something inside it does not, unless you follow up with `triggerRef()`.
  • `shallowReactive()` makes only the root-level properties reactive and stores nested values as-is, without unwrapping refs below the top level.
  • `markRaw()` permanently exempts an object from being proxied, which is the fix for class instances from libraries like map or 3D engines, and for classes with `#private` fields that break behind a Proxy.
  • `toRaw()` hands back the original object behind a proxy for a one-off untracked read or write; `readonly()` and `shallowReadonly()` hand out state consumers can read but not mutate.
  • `customRef()` lets you write your own ref by deciding when to call `track()` and `trigger()`, which is how a debounced ref is built.

When deep reactivity costs more than it gives

By default Vue’s reactivity is deep. Put an object in a ref or reactive, and every nested object becomes a Proxy the moment it is read, with every property read tracked. The previous lesson showed what that means mechanically. For a form or a todo list, it is exactly what you want.

It stops being what you want in a few predictable situations:

  • Big data you replace wholesale. A 50,000-row API response that only changes when you refetch. Tracking every cell gains nothing.
  • Objects owned by someone else. A map instance, a 3D scene, an editor, a WebSocket client. Their internals are not your state, and wrapping them in proxies can break them.
  • Classes with #private fields. Calling a method that reads this.#secret through a Proxy throws a TypeError, because the proxy, not the original instance, is this. See private fields.
  • Values that never change. A static list of countries does not need to be reactive at all.

The analogy is a security camera system. Covering every room of a warehouse is great for the rooms where people work. Pointing cameras at sealed pallets nobody opens just fills up disks. Vue gives you ways to choose where the cameras go.

shallowRef and triggerRef

import { shallowRef, triggerRef } from 'vue'

const rows = shallowRef([])

async function refresh() {
  rows.value = await fetchRows() // tracked: .value was replaced
}

function markDone(i) {
  rows.value[i].status = 'done'  // NOT tracked: nested mutation
  triggerRef(rows)               // force dependents to update
}

A shallowRef tracks one thing: assignments to .value. Whatever you store inside is kept exactly as is, with no proxy. That makes it the natural home for large immutable data, and for library instances. Swap the whole value and everything updates. Mutate inside it and nothing does, unless you call triggerRef() to say “I changed it, re-run whoever depends on this.”

Treating a shallowRef value as immutable is usually cleaner than triggerRef. Build a new array with rows.value = rows.value.map(...). It is also how state updates work in React, so the habit carries over.

shallowReactive

import { shallowReactive } from 'vue'

const state = shallowReactive({
  page: 1,
  filters: { status: 'open' },
})

state.page = 2                  // tracked
state.filters = { status: 'x' } // tracked: root-level assignment
state.filters.status = 'done'   // NOT tracked: nested object is plain

Only root-level properties are reactive. Nested values are stored and returned untouched, and refs inside are not unwrapped below the top level. It is rarer in practice than shallowRef. Mixing shallow and deep objects in one tree makes it hard to tell which writes count, so the docs advise keeping shallow objects at the root of a component’s state.

markRaw and toRaw

markRaw(obj) flags an object so Vue never turns it into a proxy, wherever it ends up:

import { reactive, markRaw } from 'vue'
import { createEditor } from 'some-editor'

const editor = markRaw(createEditor(el))
const state = reactive({ editor, wordCount: 0 })

state.editor === editor // true: the original instance, not a proxy

That is the fix when an external instance has to live inside reactive state. Note that markRaw only flags the object you pass. If you take a nested object out of it and put that into reactive state, the nested one can be proxied, and you may end up with both the raw and the proxied version of one object floating around. The docs call this an identity hazard.

toRaw(proxy) goes the other way: it returns the original object behind a reactive or readonly proxy. Use it for a one-off read or write that should not be tracked, or to pass the plain object to code that does not expect a proxy, such as structuredClone, which throws on proxies. Do not keep a long-lived reference to the raw object and keep mutating it, or you are back to changes Vue cannot see.

readonly and shallowReadonly

import { reactive, readonly } from 'vue'

const state = reactive({ count: 0 })
export const publicState = readonly(state)
export function increment() { state.count++ }

readonly() returns a proxy that is still reactive for readers but rejects writes, with a warning in development. It is a common pattern in composables and with provide and inject: hand out read access, keep mutations behind functions you control. shallowReadonly() only guards root-level properties.

customRef: deciding when to track and trigger

The lowest-level hatch is customRef, which gives you track and trigger and lets you decide when to call them. The classic example is a debounced ref:

import { customRef } from 'vue'

export function useDebouncedRef(initial, delay = 300) {
  let value = initial
  let timer
  return customRef((track, trigger) => ({
    get() {
      track()
      return value
    },
    set(next) {
      clearTimeout(timer)
      timer = setTimeout(() => {
        value = next
        trigger()
      }, delay)
    },
  }))
}

Bound with v-model, the input feels normal, but anything depending on it only re-runs once typing pauses. Most apps never need customRef, and when they do, a library such as VueUse often already has it.

The cheapest option: no reactivity at all

Before reaching for any of these, ask whether the value needs to be reactive in the first place. A timer id, a static lookup table, or a constant does not belong in a ref. A plain const or let in <script setup> works fine for values the template reads once or never. Alexander Lichter’s second video in the “go deeper” links works through four real cases of reactivity being used where it was not needed.

What the video covers

Alexander Lichter’s guide is dedicated to shallowRef: how it differs from ref, when it is the right choice (large data, external instances, signal-style immutable updates), and how VueUse and Nuxt use it internally. It does not go deep on shallowReactive, markRaw, toRaw, readonly, or customRef, which are carried above. When you profile a real app and want to apply this, performance optimization in Vue picks it up.

Where this fits

That closes out how reactive state is declared and tracked. The last piece of this group is when a component’s code runs relative to its life on the page: lifecycle hooks.

Check yourself

  1. 01A dashboard holds 50,000 rows from an API in `const rows = ref([])`, and the only change ever made is replacing the whole array after a refetch. Why is `shallowRef` a better fit, and what would break if you later started editing rows in place?

    With `ref`, Vue wraps the array, and every row object it reads, in proxies and tracks reads deep inside them, all for a dataset that is only ever swapped as a whole. `shallowRef` tracks just the `.value` assignment, which is the only change that happens, so it skips that overhead. If code later did `rows.value[3].status = 'done'`, nothing would update, because nested mutations are not tracked. You would either replace the array with a new one or call `triggerRef(rows)` after mutating.

  2. 02You store a map instance from a mapping library in `const map = ref(null)` and its methods start throwing errors or behaving strangely. What is a likely cause and fix?

    `ref` makes its object value deeply reactive, so Vue wraps the library's instance in a Proxy. Library internals that compare identity, rely on `#private` class fields, or are simply huge object graphs can break or slow down behind the proxy. Hold it in a `shallowRef`, or wrap it with `markRaw(instance)` before storing it, so Vue keeps the original object untouched.

  3. 03What is the difference between `shallowReactive({ user: { name: 'Ada' } })` and `reactive({ user: { name: 'Ada' } })` when you write `state.user.name = 'Grace'`?

    With `reactive`, the nested `user` object is also proxied when read, so changing `name` is tracked and triggers updates. With `shallowReactive`, only root-level properties are reactive. `state.user` is the plain object, so changing `name` goes unnoticed. Assigning a whole new object to `state.user` would still trigger.

  4. 04When would you use `readonly()` on state you created yourself?

    When you want to share state with other code, such as from a composable or through provide/inject, but keep writes in one place. `readonly(state)` returns a proxy that stays reactive for readers but warns in development and refuses any mutation, so consumers have to go through the functions you expose.

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