Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon What is the difference between reactive() and ref() in Vue
    Vue.js ref() reactive() Vue reactivity Vue data handling Vue.js examples


What is the difference between reactive() and ref() in Vue


The main differences between `ref()` and `reactive()` in Vue are:

1. Handling Primitive Values:
- `ref()` can store both primitive values (e.g., strings, numbers, booleans, `null`, and `undefined`) and objects.
- `reactive()` only works with objects and cannot store primitive values directly. If you need to make a primitive value reactive, use `ref()`[1][3][4].

2. Accessing Reactive Data:
- `ref()` data is accessed through the `.value` property. For example, `numberRef.value` to access the primitive value from the ref.
- `reactive()` data is accessed directly without needing the `.value` property. For example, `objectReactive.count` to access a property of the reactive object[1][2][3].

3. Reassigning Data:
- `ref()` allows reassigning the value of the ref without losing reactivity. For example, `user.value = { name: 'Jim Halpert' }` in the example below.
- `reactive()` objects are immutable by default. If you reassign the entire object, the reactivity is lost. For example, `Object.assign(modified, original)` in the example below[3][5].

Here is an example of using `ref()` and `reactive()`:

javascript
<script setup>
  import { ref, reactive } from 'vue';

  // Using ref()
  const count = ref(0);
  console.log(count.value); // logs 0
  count.value = 1;
  console.log(count.value); // logs 1

  // Using reactive()
  const user = reactive({ name: 'Michael Scott' });
  console.log(user.name); // logs Michael Scott
  user.name = 'Jim Halpert';
  console.log(user.name); // logs Jim Halpert
</script>

In summary, `ref()` is more flexible and can handle primitive values, while `reactive()` is more suitable for objects and provides a more straightforward way of accessing reactive data.

Citations:
[1] https://dmitripavlutin.com/ref-reactive-differences-vue/
[2] https://michaelnthiessen.com/ref-vs-reactive
[3] https://stackoverflow.com/questions/61452458/ref-vs-reactive-in-vue-3
[4] https://vuejsdevelopers.com/2022/06/01/ref-vs-reactive/
[5] https://www.telerik.com/blogs/should-use-ref-reactive-vue-3