Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ref vs shallowRef for simple variables like string or number

Tags:

vue.js

vuejs3

I know that shallowRef is lighter for resources because it watches only for changes in array keys or direct value changes. It does not watch, for example, deep inside object fields. Cool.

But what about strings or numbers. Does it make any sense to use shallowRef instead ref for those? Does it have any impact?

Or maybe ref for strings is by default shallow?

My thinking is - maybe it's better to ALWAYS use shallowRef for all data, and change it to normal ref ONLY when it's really needed (for ex. array with objects). This way, I will never use more resource consuming ref by mistake when it's not really needed.

like image 532
norr Avatar asked Mar 30 '26 19:03

norr


1 Answers

TLDR:

For primitive types (string, number etc.) it does not make a difference, it's the same (with a very small ref() overhead)

The docs state;

shallowRef() is typically used for performance optimizations of large data structures, or integration with external state management systems.

Unlike ref(), the inner value of a shallow ref is stored and exposed as-is, and will not be made deeply reactive. Only the .value access is reactive.

Use

ref() when..

  • it's a primitive (for example 'string', true, 23, etc)
  • it's an object you need to later reassign (like an array - more info here)

shallowRef() when..

  • To avoid the deep conversion
  • For big data structure where no deep reactivity is needed

reactive() when..

  • it's an object you don't need to reassign, and you want to avoid the overhead of ref() (no .value access, see below)

reactivity fun facts

  • reactive() only takes objects, NOT JS primitives (String, Boolean, Number, BigInt, Symbol, null, undefined)
  • ref() is calling reactive() behind the scenes

Since reactive() works for objects and ref() calls reactive(), objects work for both BUT, ref() has a .value property for reassigning, reactive() does not have this and therefore CANNOT be reassigned

like image 137
nonNumericalFloat Avatar answered Apr 02 '26 05:04

nonNumericalFloat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!