Sobes.tech
Senior

What is the difference between ref and shallowRef in Vue.js? When is it better to use shallowRef?

sobes.tech AI

Answer from AI

In Vue.js, ref and shallowRef create reactive objects but differ in the depth of reactivity.

  • ref makes the value reactive deeply: if it's an object, Vue recursively makes all nested properties reactive.

  • shallowRef creates reactivity only at the top level — the object itself is tracked, but nested properties are not reactive.

When to use shallowRef:

  • If you have a large or complex object that rarely changes entirely, and you want to avoid the overhead of deep reactivity.
  • When working with objects that are already reactive or managed outside Vue (e.g., third-party libraries), and you don't want Vue to make their properties reactive.
  • For performance optimization, to avoid unnecessary reactive wrappers.

Example:

import { ref, shallowRef } from 'vue';

const deep = ref({ a: 1, b: { c: 2 } });
const shallow = shallowRef({ a: 1, b: { c: 2 } });

// Changing deep.value.b.c will be tracked and trigger updates
// Changing shallow.value.b.c — no, because the nested object is not reactive

Thus, shallowRef is useful when only top-level reactivity is needed, and nested data should not trigger reactive updates.

What is the difference between ref and shallowRef in… - sobes.tech