惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

G
Google Developers Blog
S
Schneier on Security
The Hacker News
The Hacker News
P
Proofpoint News Feed
Spread Privacy
Spread Privacy
L
LINUX DO - 热门话题
L
Lohrmann on Cybersecurity
I
Intezer
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Schneier on Security
Schneier on Security
Security Latest
Security Latest
AWS News Blog
AWS News Blog
B
Blog RSS Feed
Microsoft Security Blog
Microsoft Security Blog
有赞技术团队
有赞技术团队
博客园 - 叶小钗
The Last Watchdog
The Last Watchdog
O
OpenAI News
月光博客
月光博客
Hacker News: Ask HN
Hacker News: Ask HN
阮一峰的网络日志
阮一峰的网络日志
S
Security @ Cisco Blogs
Google Online Security Blog
Google Online Security Blog
云风的 BLOG
云风的 BLOG
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Latest news
Latest news
P
Palo Alto Networks Blog
Last Week in AI
Last Week in AI
M
MIT News - Artificial intelligence
Google DeepMind News
Google DeepMind News
P
Proofpoint News Feed
C
CERT Recently Published Vulnerability Notes
Apple Machine Learning Research
Apple Machine Learning Research
U
Unit 42
PCI Perspectives
PCI Perspectives
博客园 - 聂微东
SecWiki News
SecWiki News
宝玉的分享
宝玉的分享
Forbes - Security
Forbes - Security
H
Heimdal Security Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Hugging Face - Blog
Hugging Face - Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
T
Troy Hunt's Blog
博客园 - 三生石上(FineUI控件)
Application and Cybersecurity Blog
Application and Cybersecurity Blog
罗磊的独立博客
WordPress大学
WordPress大学
D
Darknet – Hacking Tools, Hacker News & Cyber Security

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
5 Must-Know Differences Between ref() and reactive() in Vue
Dmitri Pavlutin · 2023-01-25 · via Dmitri Pavlutin Blog

If you landed on this post, you probably have a basic understanding of Vue reactivity.

However, like me, you might be asking yourself the eternal question: what are the main differences between ref() and reactive()? And when to use one or another?

Let's find the answer together.

Table of Contents

  • 1. Primitive values
  • 2. Accessing reactive data
  • 3. Reassigning data
  • 4. Typing
  • 5. Watching
  • 6. Usage
  • 7. Conclusion

1. Primitive values

ref() and reactive() handle differently primitive values: strings, numbers, booleans, null, and undefined.

1.1 ref()

refs() stores both primitive values and objects:


import { ref } from 'vue'

const numberRef = ref(0); // OK

const objectRef = ref({ count: 0 }) // OK


In the example above ref(0) creates a ref storing a primitive value.

Same way, ref({ count: 0 }) creates a ref storing a plain JavaScript object.

1.2 reactive()

On the other side, reactive() doesn't store primitives, but stores only objects:


import { reactive } from 'vue'

const numberReactive = reactive(0); // NOT OK!

const objectReactive = reactive({ count: 0}); // OK


Calling reactive(0) with a primitive value is incorrect. Don't do this. If you need to make reactive primitive values, ref(0) is the way to go.

The reason why reactive() works only with objects is in Vue's reactivity implementation. Vue uses Proxies to intercept property changes on objects. And proxies do not work with primitives.

Nevertheless, reactive({ count: 0}) initialized with an object is perfectly valid and creates a reactive object.

In conclusion:

ref() can store primitive values, while reactive() cannot.

2. Accessing reactive data

The second difference is how you'd access the data stored inside ref() and reactive().

2.1 ref()

ref() data, either a primitive value or an object, is accessed through a special property .value:


import { ref } from 'vue'

const numberRef = ref(0);

console.log(numberRef.value); // logs 0

const objectRef = ref({ count: 0 })

console.log(objectRef.value.count); // logs 0


numberRef.value is how you access the primitive value from the ref numberRef.

<ref>.value is a special property available on all the refs to read or update the ref value.

Also, objectRef.value.count is how you can access a property of an object in ref.

Note that inside templates you don't have to use .value to access a ref value: they're auto-unwrapped.


<script setup>

import { ref } from 'vue'

const numberRef = ref(0)

</script>

<template>

<div>{{ numberRef }}</div> <!-- <div>0</div> -->

</template>


Open the demo.

In the interpolation {{ numberRef }} the ref is auto-unwrapped.

2.2 reactive()

reactive() data, on the other hand, is accessed directly:


import { reactive } from 'vue'

const objectReactive = reactive({ count: 0})

console.log(objectReactive.count) // logs 0


Accessing reactive data created using reactive({ count: 0} ) doesn't need additional syntax and is done directly: objectReactive.count.

The reactive object returned by reactive(originalObject) is a proxy object of originalObject. Meaning that the reactive object has the same properties (aka has the same interface) as the originalObject.

In conclusion:

ref() data is accessed using value property (exception: in templates the ref is auto-unwrapped), while reactive() data is accessed directly.

3. Reassigning data

ref() is accessed and updated using .value property, while reactive() is a proxy of the original object. As result ref() can be reassigned to an new object, while reactive() cannot.

ref()

Reassigning the value of a ref() entirely to a new value is perfectly valid:


<script setup>

import { ref, onMounted } from "vue"

const objectRef = ref({ count: 0 })

onMounted(() => objectRef.value = { count: 1 })

</script>

<template>{{ objectRef.count }}</template>


Open the demo.

Open the demo, and see that replacing entirely the ref value objectRef.value = { count: 1 } after mounting is reflected in the output. The reactivity is kept.

reactive()

Reassigning entirely a reactive() object, however, is not possible:


<script setup>

import { reactive, onMounted } from 'vue'

let objectReactive = reactive({ count: 0})

onMounted(() => objectReactive = { count: 1 })

</script>

<template>{{ objectReactive.count }}</template>


Open the demo.

Open the demo, and see that replacing entirely the reactive object value objectReactive = { count: 1 } after mounting is not reflected in the output. Doing so breaks the reactivity of objectReactive.

In conclusion:

ref() value can be reassigned entirely to a new object, while a reactive() cannot.

4. Typing

ref()

A direct consequence of ref data being accessed through .value property is how refs are typed.

To annotate a ref you need to use a special type Ref, available for importing from vue library:


import { ref, Ref } from 'vue'

const numberRef: Ref<number> = ref(0);


Ref<number> is the type meaning a ref holding a number.

If you want to assign a ref as an argument to a composable, for example, then make sure to use the Ref<V> type (where V is the value's type) to annotate a ref parameter:


import { ref, Ref } from 'vue'

const numberRef: Ref<number> = ref(0)

export const useIsEven = (numberRef: Ref<number>) => {

return computed(() => numberRef.value % 2 === 0)

}

const isEven = useIsEven(numberRef) // type check passed


reactive()

On the other hand, reactive data returned by reactive() is typed as the initial object:


import { reactive } from 'vue'

const objectReactive: { count: number } = reactive({ count: 0})


reactive({ count: 0}) returns an object of type { count: number }. The reactive object normally keeps the type of the original object.

But there's one exception — if the reactive object contains refs, then these refs are unwrapped.


import { reactive, ref } from 'vue'

const objectReactive: { count: number } = reactive({ count: ref(0)})


Even though the reactive object is { count: ref(0) }, the returned type is still { count: number }. All because reactive() automatically unwraps the refs found in the reactive object.

In conclusion:

refs returned by ref(value: T) are of type Ref<T>, while reactive objects returned by reactive(object: T) are of type T (exception: refs in reactive are unwrapped).

5. Watching

watch() watches reactive data change. The default behavior of watch() differs for ref() and reactive().

ref()

watch() determines if .value property of the ref is changed:


<script setup>

import { ref, watch } from 'vue'

const countNumberRef = ref(0)

watch(countNumberRef, () => {

console.log('changed!')

})

const increase = () => countNumberRef.value++

</script>

<template>

{{ countNumberRef }}

<button @click="increase">Increase</button>

</template>


Open the demo.

Every time you click the "Increase" button, you'll see in the console the message "changed!". watch(count, callback) calls callback every time countNumberRef.value changes.

But does watch() watch deep changes of an object stored in ref()? Let's try!


<script setup>

import { ref, watch } from 'vue'

const countObjectRef = ref({ count: 0 })

watch(countObjectRef, () => {

console.log('changed!')

})

const increase = () => countObjectRef.value.count++

</script>

<template>

{{ countObjectRef.count }}

<button @click="increase">Increase</button>

</template>


Open the demo.

This time, however, if you click the "Increase" button there will be no message in the console! The conclusion is that watch() doesn't deeply watch refs by default.

However, DOM still updates when countObjectRef.value.count changes: which means the object in the ref is still reactive in regards to the rendered output.

Of course, if you ask watch() to watch the ref deeply, it's working as full deep watch:


// ...

watch(count, () => {

console.log('changed!')

}, { deep: true })

// ...


Open the demo.

reactive()

In the case of watching a reactive object, watch() always performs a deep watch (even if you don't indicate { deep: true }) option.


<script setup>

import { reactive, watch } from 'vue'

const countObjectReactive = reactive({ counter: { val: 0 } })

watch(countObjectReactive, () => {

console.log('changed!')

})

const increase = () => countObjectReactive.counter.val++

</script>

<template>

{{ countObjectReactive.counter.val }}

<button @click="increase">Increase</button>

</template>


Open the demo.

Every time you click the "Increase" button, you'll see in the console the message "changed!". watch(countObjectReactive, callback) calls callback every time any property (even a deep one) of countObjectReactive changes.

In conclusion:

watch() by default watches only direct .value change of ref(), while doing a deep watch of a reactive() object.

6. Usage

While there isn't a strict rule, still, there are situations when using a specific reactivity function is preferable:

  1. If you need a reactive primitive value, then using ref() is the right choice.
  2. If you need a reactive value object (an object whose properties usually don't change), then using ref() is a good option.
  3. If you need a reactive mutable object, and you want to track even the deeply mutated properties of that object, then using reactive() is a good option.

7. Conclusion

This post presented the differences between ref() and reactive() in composition API:

  1. ref() can store a primitive value, while reactive() cannot.
  2. You access the value stored in a ref() using <ref>.value, while reactive() object can be used directly as a regular object.
  3. ref() value can be reassigned to an entirely new object, while reactive() cannot.
  4. ref() is typed as Ref<V>, while the reactive object returned by reactive(originalObject) usually maintains the type of the originalObject.
  5. watch() (when used without options) normally watches only direct changes of <ref>.value, while watching deeply reactive() objects.

You'd use ref() to store primitives or value objects, but reactive() if you're interested to watch deep changes of a mutable object.

What other differences between ref() and reactive() do you know?