Vue3 Fundamentals · Reactivity

Opt out of deep reactivity

shallowRef

Opt out of deep reactivity

ref makes a value deeply reactive: Vue watches every nested property. For a large object you rarely touch inside, that tracking is wasted work. shallowRef tracks only .value itself.

<script setup>
import { shallowRef } from 'vue';

const state = shallowRef({ count: 0 });

function increment() {
  state.value = { count: state.value.count + 1 };
}
</script>

<template>
  <button @click="increment">Count: {{ state.count }}</button>
</template>

Because the ref is shallow, changing state.value.count directly would not trigger a render. Replacing state.value with a new object does, so the button builds a fresh object each time.

Use shallowRef for a value you replace wholesale — a big list, a fetched record, an immutable snapshot. shallowReactive is the same idea for an object: only its top-level properties are tracked.

The Test for this Lesson mounts your component, clicks the button once, and checks the label. Your component is exported from App.vue.

Challenge

The button mutates a nested property, so nothing re-renders. Replace the value instead: export an App component from App.vue that holds the state in a shallowRef and renders a button labelled Count: 0, adding one on each click.

The Test mounts your component, clicks the button once, and expects the label to read Count: 1. The starter mutates state.value.count, which a shallow ref does not track, so the label stays Count: 0 and the Test fails.

App.vue
<script setup>
import { shallowRef } from 'vue';

const state = shallowRef({ count: 0 });

function increment() {
  state.value.count += 1;
}
</script>

<template>
  <button @click="increment">Count: {{ state.count }}</button>
</template>

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.